PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python DateTime

Python DateTime

In this series, you will learn how to use a date and time in Python. Dealing with dates and times can be complicated, but fortunately, we have many open-source libraries available in Python to work with it.

Date and Time Series

This Python Date and Time Series contains the following in-depth tutorial. You can directly read those.

  • Get Current Date and Time in Python: You'll learn to get the current date and time in Python using the datetime and time module.
  • Python DateTime Format Using Strftime(): You'll learn to represent date and time in various formats in Python using the strftime() function of a datetime module and time module. For example, represent a date numerically in format, like “17-06-2021“ or textual string format like “Tuesday, 23 June 2021.”
  • Python String to DateTime using strptime(): You'll learn to parse a string representing a date or time to a datetime using the strptime() with the various standard date formatting codes available in Python
  • Timestamp In Python: You'll learn to work with timestamp. Convert datetime to timestamp and vice-versa. Format timestamp to string object and vice-versa
  • TimeDelta in Python: You'll learn to calculate the difference between two datetime using timedelta. How to use the timedelta class to calculate future dates and past dates.
  • Working With TimeZones in Python: You'll learn the handling of timezone by creating a timezone-aware date and time. Get the current time in a different time zone. Get timezone name, UTC offset, and DST offset if DST is in effect and perform timezone conversion

FAQs:

The below list contains the solution to the common questions and challenges you can face working with datetime in Python.

  • Python Difference Between Two Dates in Days
  • Python Difference Between Two Dates in Months and Years
  • Calculate Time Difference in Python
  • Python Get the Day of the Week
  • Python Get Business Days
  • Python Measure the Execution Time of a Program
  • Python Get ISO 8601 Datetime
  • Python Datetime to Seconds
  • Python Convert Seconds To hh:mm:ss (Hours, Minutes, and Seconds)
  • Python Get File Creation and Modification DateTime

Below is the list of standard libraries we can use to work with date and time.

  • datetime: The datetime is a built-in module that provides functions to handle many complex functionalities involving the date and time. It has a date, time, timezone, and timedelta classes to work with date and time.
  • calendar: In Python, a calendar is a built-in module to work with calendar-related activities and operations. In the calendar module, by default, Monday is the first day of the week, and Sunday is the last day of the week as per the Gregorian calendar.
  • time: time module provides a different function to work with time-related activities where dates are not needed.

Get Current Date and Time in Python

Import a datetime module using the import statement like import datetime and you are good to go.

The datetime module has a datetime class that contains the current local date and time. Use the now() method to access the current date and time.

Example:

from datetime import datetime

# get current date and time
now = datetime.now()
print(now)

# print class
print(type(now))

Output:

2021-06-04 10:24:04.646972
<class 'datetime.datetime'>

As you can see in the output we got the current date and time in the following format.

YYYY-MM-DD HH:MM:SS.MS

Read More: How to get Current Date and Time in Python to learn various other ways to get the current datetime, local time, UTC time, GMT time, and ISO time. Also, learn to get the current time in the specific timezone.

Classes In The Datetime Module

Python provides the dir() function to list all attributes and functions of a module. Let's see the constants and classes of a datetime module.

import datetime
print(dir(datetime))

Output:

['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']

Each class has various methods to access and manipulate dates and times. We'll learn each one by one.

  • date Class
  • time Class
  • datetime Class
  • timedelta Class

Date Class in DateTime

We can represent the date object using the date class and the date class initializes the native date. It always considers the Gregorian calendar.

The constructor of the date class takes three parameters which include year, month, and day.

Syntax to create a date object:

datetime.date(year, month, day)

The arguments should be in the following range :

  • MINYEAR <= year <= MAXYEAR
  • 1 <= month <= 12
  • 1 <= day <= number of days in the given month and year

If we pass an argument outside of given ranges, ValueError is raised.

Example: Create a date object in Python.

from datetime import date

date1 = date(2021, 2, 10)
print("Date is :", date1)

Output:

Date is : 2021-02-10

Get Today's Date

The date.today() function returns the current local date.

from datetime import date

# Get today's date
today = date.today()
print('Today:', today)

# extract attributes
print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)

Output:

Today: 2021-07-16
Year: 2021
Month: 7
Day: 16

Time Class

As you know, the datetime object contains both date and time. To work only with time, we can use the time class from the datetime module.

To represent the local time, we can instantiate the time object from the time class. The arguments for time class are optional.

Syntax to create a time object:

datetime.time(hour, minute, second, microsecond, tzinfo, *, fold)

The arguments should be in the following range:

  • 0 <= hour < 24,
  • 0 <= minute < 60
  • 0 <= second < 60
  • 0 <= microsecond < 1000000
  • fold in [0, 1]
  • tzinfo is the timezone information.

If we pass an argument outside of given ranges, ValueError is raised.

Example:

from datetime import datetime
from datetime import time

# Extract time from datetime object
now = datetime.now()
print("Current time is:", now.time())

# Create empty time object
t = time()
print('Time', t)

# create time object with attribute names
t1 = time(hour=7, minute=10, second=34)
print("time is:", t1)

# time without attributes names
t2 = time(7, 10, 45)
print("time is:", t2)

# time with microseconds
t3 = time(7, 10, 45, 400437)
print("time is:", t3)

Output:

Current time is: 12:23:20.308263
Time 00:00:00
time is: 07:10:34
time is: 07:10:45
time is: 07:10:45.400437

Extract Hours, Minutes, Second from Time Object

The time class provides the following attributes to access the induvial component such as a hours, minutes, seconds, microseconds from a time object.

Example:

from datetime import datetime

# Extract time from datetime object
t = datetime.now().time()
print('Time is:', t)

print('Hours', t.hour)
print('Minutes', t.minute)
print('Seconds', t.second)
print('Microseconds', t.microsecond)

Output:

Time is: 12:32:24.208371
Hours 12
Minutes 32
Seconds 24
Microseconds 208371

Datetime Class

The datetime class contains information about both date and time. It Assumes the Gregorian Calendar and there are 360*24 seconds every day.

Create datetime object

datetime.datetime(year, month, day, hour, minute=0, second, microsecond, tzinfo=None)

Arguments must be integers in the following ranges:

  • MINYEAR <= year <= MAXYEAR,
  • 1 <= month <= 12,
  • 1 <= day <= number of days in the given month and year,
  • 0 <= hour < 24,
  • 0 <= minute < 60,
  • 0 <= second < 60,
  • 0 <= microsecond < 1000000,
  • fold in [0, 1].

If we pass an argument outside of given ranges, ValueError is raised.

Example: Create a datetime object

# import datetime class
from datetime import datetime

# Get current date and time
now = datetime.now()
print('Current datetime:', now)

# create datetime object
dt = datetime(year=2021, month=2, day=17, hour=13, minute=47, second=34)
print("Datetime is:", dt)

Output:

Current datetime: 2021-07-16 12:35:58.497313
Datetime is: 2021-02-17 13:47:34

Get Date, Time, TimeStamp from Datetime

The datetime module provides several attributes and functions to access the induvial component such as a date, time, timestmap, year, month, day, hour, minute, seconds.

Example:

from datetime import datetime

# create datetime object
dt = datetime.now()
print("Datetime is:", dt)

# Get date, time, and timestamp
print('Date:', dt.date())
print('Time:', dt.time())
print('Timestamp:', dt.timestamp())

# Get Attributes
print('Year:', dt.year)
print('Month:', dt.month)
print('Day:', dt.day)

print('Hours:', dt.hour)
print('Minutes:', dt.minute)
print('Seconds:', dt.second)
print('Microseconds:', dt.microsecond)

Output:

Datetime is: 2021-07-16 12:43:14.701186
Date: 2021-07-16
Time: 12:43:14.701186
Timestamp: 1626419594.701186

Year: 2021
Month: 7
Day: 16

Hours: 12
Minutes: 43
Seconds: 14
Microseconds: 701186

Create DateTime from Timestmap

We can convert the timestamp back to datetime object using the fromtimestamp() method that is available in the both date and datetime class.

It returns the local date and time corresponding to the POSIX timestamp.

from datetime import datetime

# timestamp
ts = 1617295943.17321

# convert to datetime
dt = datetime.fromtimestamp(ts)
print("The date and time is:", dt)

# output 2021-04-01 22:22:23.173210

Read More: Working with Timestamp in Python

Python DateTime Formatting

DateTime to String

We can represent date and time into various formats in Python using the strftime() function of a datetime module and time module.

The strftime() method returns a string representing of a datetime object according to the format codes.

Example: Convert a datetime to the string format of dd/mm/yyyy hh:mm:ss.

from datetime import datetime

# current dateTime
now = datetime.now()

# convert to string
date_time_str = now.strftime("%d/%m/%Y %H:%M:%S")
print('DateTime String:', date_time_str)

# output 23/06/2021 08:44:18

Read More: Python DateTime Format Using Strftime()

String to DateTime

We can parse a string to a datetime object using the strptime() with the various standard date formatting codes available in Python.

Example: Convert String to Datetime

Let us see with an example where we have a string representing the date and time in the standard format (dd/mm/yyyy hh:mm:ss).

from datetime import datetime

# Date String in dd/mm/yyyy HH:MM:SS format
dt_string = "12/06/2021 09:15:32"

# Convert string to datetime object
dt_object = datetime.strptime(dt_string, "%d/%m/%Y %H:%M:%S")
print(dt_object)

# Output 2021-06-12 09:15:32

Read More: Python String to DateTime using strptime()

TimeDelta: Differance Between Two DateTime

A timedelta represents a duration which is the difference between two dates, time, or datetime instances, to the microsecond resolution.

Using the datetime moduel's timedelta class we can add or subtract weeks, days, hours, minutes, seconds, microseconds, and milliseconds from a given date and time.

Also, we can calculate the difference between two datetime.

Example:

from datetime import datetime

# given datetime
current_date = datetime.now()
x_date_time = datetime(year=2020, month=3, day=21, hour=12, minute=30)

# Difference between two dates
# Get timedelta
timedelta = current_date - x_date_time

print('Differance:', timedelta)
print(type(timedelta))

Output:

Differance: 469 days, 20:39:07.830124
<class 'datetime.timedelta'>

Read More: TimeDelta in Python.

Handling TimeZone in Python

A time zone represents the standardized time depending on which part of the world is being considered.

The pytz library has implemented a timezone class for handling arbitrary fixed offsets from UTC and timezones.

In Python, a date object can be mentioned with or without timezones. Based on that, an object is known as Naive or Aware. A date object, by default, is naive. A datetime or time object is aware if it holds the timezone(tz) value.

Example: Create a timezone-aware datetime in Python.

from datetime import datetime
import pytz

# current Datetime
unaware = datetime.now()
print('Timezone naive:', unaware)

# US/Central timezone datetime
aware_us_central = datetime.now(pytz.timezone('US/Central'))
print('US Central DateTime', aware_us_central)

Output:

Timezone naive: 2021-07-09 13:22:02.256978
US Central DateTime 2021-07-09 02:52:02.313026-05:00

Read More:

  • Working with timezone in Python
  • List All TimeZones in Python

Python Time module

Python time module provides various functions to perform time-related activities. Following are the most commonly used functions of the time module.

Function Description
time.time() Return the time in seconds since the epoch as a floating point number
time.sleep(sec) Suspend execution of the calling thread for the given number of seconds
time.ctime(sec) Convert a time expressed in seconds since the epoch to a string of a form: 'Sun Jun 20 23:21:05 2021' representing local time
time.localtime(sec) Convert a time expressed in seconds since the epoch to a local time in the a struct_time format
time.mktime(t) It returns the time in seconds that has lapsed/passed since the epoch. This is the inverse function of localtime()
time.gmtime(sec) Convert a time expressed in seconds since the epoch to a struct_time in UTC format in which the dst flag is always zero
time.strptime(str, format) Convert a string representing the time according to a format. Return value is The return value is a struct_time
time.strftime(format[, t]) Convert a tuple or struct_time representing a time to a string according to a format.
time.asctime(t) Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11 18:07:14 2008'.
Time Module Functions

Example

import time

seconds = time.time()
print("Current time in seconds:", seconds)

local_time = time.localtime(seconds)
print('Local Time', local_time)

# time in string form
print('Time in String:', time.ctime(seconds))

# Formatting the time to display in string format
print('Formatted Time:', time.strftime("%d/%m/%Y %H:%M:%S", local_time))

# String to Time Object
print('Time object:', time.strptime("16/07/2021 17:33:37", "%d/%m/%Y %H:%M:%S"))

Output:

Current time in seconds: 1626437772.1504333

Local Time time.struct_time(tm_year=2021, tm_mon=7, tm_mday=16, tm_hour=17, tm_min=46, tm_sec=12, tm_wday=4, tm_yday=197, tm_isdst=0)

Time in String: Fri Jul 16 17:46:12 2021

Formatted Time: 16/07/2021 17:46:12

Time object: time.struct_time(tm_year=2021, tm_mon=7, tm_mday=16, tm_hour=17, tm_min=33, tm_sec=37, tm_wday=4, tm_yday=197, tm_isdst=-1)

Python Calender Module

Python has a built-in module called calendar for calendar-related activities. This module supplies calendar-related functions, including functions to print a text calendar for a given month or year.

By default, the calendar takes Monday as the first day of the week and Sunday as the last one. We can also change this for that we can use calendar.setfirstweekday() function. To use the calendar first, we need to Import it.

The below table shows the list of functions available with the calendar module.

Function Description
calendar.firstweekday( ) Returns the current setting for the weekday that starts each week. By default, when the calendar is first imported, this is 0, meaning Monday.
calendar.isleap(year) Returns True if the year is a leap year; otherwise, False.
calendar.leapdays(y1,y2) Returns the total number of leap days in the years within range(y1,y2).
calendar.month(year,month,w=2,l=1) Returns a multiline string with a calendar for month of the year, w is the width in characters of each date. l is the number of lines for each week.
calendar.monthcalendar(year,month) Returns a list of lists. Each sublist denotes a week.
calendar.monthrange(year,month) It returns two integers. The first one is the code of the weekday for the first day of the month in year and second is the number of days in the month. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12
calendar.setfirstweekday(weekday) it returns sets the first day of each week to a weekday. Weekday codes are 0 (Monday) to 6 (Sunday)
calendar.timegm(tupletime) It accepts a time instant in time-tuple form and returns the same instant as a floating-point number of seconds
calendar.weekday(year,month,day) It returns the weekday code for the given date. Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 (January) to 12 (December).
Calendar module functions

Example

import calendar

year = 2021
month = 6

# Display calendar
print(calendar.month(year, month))

Output

     June 2021
Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

All Date and Time Tutorials

Python Create List Of Dates Within Range

Updated on: March 9, 2023 | Leave a Comment

Filed Under: Pandas, Python, Python DateTime

Python Get Month Name From Number

Updated on: October 13, 2022 | Leave a Comment

Filed Under: Python, Python DateTime

Python Compare Two Dates

Updated on: October 10, 2022 | Leave a Comment

Filed Under: Python, Python DateTime

Python Get Last Day of Month

Updated on: October 7, 2022 | Leave a Comment

Filed Under: Python, Python DateTime

Python Get First Day Of Month

Updated on: September 26, 2022 | 1 Comment

Filed Under: Python, Python DateTime

Python ISO 8601 Datetime

Updated on: May 27, 2022 | 1 Comment

Filed Under: Python, Python DateTime

Python Datetime to Seconds

Updated on: May 17, 2022 | Leave a Comment

Filed Under: Python, Python DateTime

Calculate Time Difference in Python

Updated on: May 16, 2022 | 3 Comments

Filed Under: Python, Python DateTime

Python Get Business Days

Updated on: May 16, 2022 | 1 Comment

Filed Under: Python, Python DateTime

Python Get the Day of the Week

Updated on: May 10, 2022 | 2 Comments

Filed Under: Python, Python DateTime

Python Difference Between Two Dates in Months and Years

Updated on: May 6, 2022 | 1 Comment

Filed Under: Python, Python DateTime

Python Difference Between Two Dates in Days

Updated on: October 7, 2022 | Leave a Comment

Filed Under: Python, Python DateTime

Python Measure the Execution Time of a Program

Updated on: February 23, 2022 | 2 Comments

Filed Under: Python, Python DateTime

Python Get File Creation and Modification DateTime

Updated on: February 17, 2022 | 1 Comment

Filed Under: Python, Python DateTime, Python File Handling

Python Convert Seconds To hh:mm:ss (Hours, Minutes, and Seconds)

Updated on: February 17, 2022 | Leave a Comment

Filed Under: Python, Python DateTime

How to Get Current Date and Time in Python

Updated on: December 5, 2021 | 2 Comments

Filed Under: Python, Python DateTime

List All TimeZones in Python

Updated on: December 5, 2021 | 1 Comment

Filed Under: Python, Python DateTime

Working With TimeZones in Python

Updated on: December 5, 2021 | 1 Comment

Filed Under: Python, Python DateTime

Python String to DateTime using strptime()

Updated on: December 5, 2021 | 2 Comments

Filed Under: Python, Python DateTime

Python DateTime Format Using Strftime()

Updated on: May 6, 2022 | 3 Comments

Filed Under: Python, Python DateTime

Timestamp In Python

Updated on: December 5, 2021 | 1 Comment

Filed Under: Python, Python DateTime

Timedelta in Python

Updated on: December 5, 2021 | 3 Comments

Filed Under: Python, Python DateTime

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com