Python datetime

Unlike other programming languages, Python doesn’t allow us to work with Date objects directly. To work with date and time objects, you have to import a module called datetime in Python. This Python datetime module holds different classes to work with dates or to manipulate dates and times.

Learn how to import datetime in Python, work with date and time objects, format datetime, timedelta with practical examples. To import the Python datetime module.

import datetime 

The syntax of this Python datetime is

datetime.datetime(Year_Number, Month_Number, Day_Number, Hours, Minutes, Seconds)

Python datetime examples

Let me show you the list of available methods in this Python datetime module. For this, you have to use the Python datetime as the dir function argument.

# datetime Example
 
import datetime
 
print(dir(datetime))

List of available methods in Python datetime module.

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

The MAXYEAR returns the maximum(highest) year supported by the Python datetime module, i.e., 9999. The MINYEAR returns the smallest allowed year, i.e., 1.

import datetime
 
print('Maximum Year  = ', datetime.MAXYEAR)
print('Minimum Year  = ', datetime.MINYEAR) 

datetime MAXYEAR and MINYEAR output

Maximum Year  =  9999
Minimum Year  =  1

The following datetime example uses the Python today method to returns the current date.

import datetime
 
dt = datetime.date.today()
 
print('Today\'s Date = ', dt)

datetime today function output

Today's Date =  2021-05-03

Python datetime class

This class has attributes of year, month, and day. Here, the first print statement extracts and returns the Year from the current date. The next two print statement returns Month number and Day.

import datetime
 
today = datetime.date.today()
 
print('Today\'s Date = ', today)
print('Year from Today\'s Date = ', today.year)
print('Month from Today\'s Date = ', today.month)
print('Day from Today\'s Date = ', today.day)

datetime class output

Today's Date =  2021-05-03
Year from Today's Date =  2021
Month from Today's Date =  5
Day from Today's Date =  3

Python datetime now

The Python datetime module has now function, which returns the current date and time.

import datetime
 
dt = datetime.datetime.now()
print(dt)
 
print('Today\'s Date and Time = ', dt)

datetime now function

2021-05-03 16:03:25.186286
Today's Date and Time =  2021-05-03 16:03:25.186286

Until now, we are using the import datetime, and that was the reason we are using datetim.datetime.method_name. However, if we use from datetime import datetime, we can get rid of that extra datetime.

See the available date and time functions in Python datetime to extract and return date, time from the current date & time.

from datetime import datetime
 
dt = datetime.now()
 
print('Date and time  = ', dt)
print('Current Date   = ', dt.date())
print('Current Time   = ', dt.time())

Extracting date and time from current date written by datetime

Date and time  =  2021-05-03 16:02:43.706407
Current Date   =  2021-05-03
Current Time   =  16:02:43.706407

Python datetime class attributes

It returns the Year from the current date and time.

import datetime
 
dt = datetime.datetime.now()
 
print('Today\'s Date and Time = ', dt)
 
print('Calendar Year = ', dt.year)

datetime class attribute output

Today's Date and Time =  2021-05-03 16:01:05.917863
Calendar Year =  2021

This example displays the list of all the available attributes in Python datetime class. They are Year, Month, Day of Month, hour, minute, second, microsecond, and weekday.

from datetime import datetime
 
dt = datetime.now()
 
print('Date = ', dt)
print('Year from Date        = ', dt.year)
print('Month from Date       = ', dt.month)
print('Day from Date         = ', dt.day)
print('Hour from Date        = ', dt.hour)
print('Minute from Date      = ', dt.minute)
print('Second from Date      = ', dt.second)
print('Microsecond from Date = ', dt.microsecond)
print('Weekday Number from Date = ', dt.weekday())
Date =  2021-05-03 16:00:39.908339
Year from Date        =  2021
Month from Date       =  5
Day from Date         =  3
Hour from Date        =  16
Minute from Date      =  0
Second from Date      =  39
Microsecond from Date =  908339
Weekday Number from Date =  0

The Python datetime module has the time class used to work or manipulate time values. Here, we used the time class to write the time from the current date and time. Next, we used the print statement to return the time parts using the available attributes hour, minute, second, and microsecond.

from datetime import datetime
 
time = datetime.time(datetime.now())
 
print('Current Time                  = ', time)
print('Hour from Current Time        = ', time.hour)
print('Minute from Current Time      = ', time.minute)
print('Second from Current Time      = ', time.second)
print('Microsecond from Current Time = ', time.microsecond)
Python datetime 9

Python isoformat

The Python datetime class has the isoformat, which returns a string representation of a date in ISO 8601 format of YYYY-MM-DD

from datetime import datetime
 
print(datetime.now())
print(datetime.now().isoformat())

datetime isoformat function output

2021-05-03 16:05:47.074065
2021-05-03T16:05:47.103824

In all our previous datetime examples, we are working with the current date and time using now or today. However, you can use the date function to create a custom date. Here, we are using the custom date and returning it in iso format.

from datetime import date
 
dt = date(2018, 1, 31)
print(dt)
print(dt.isoformat())
2018-01-31
2018-01-31

Create Date and Time using Python datetime module

Using the datetime function to create a custom date. This function accepts year, month, day, hour, minute, second, and microsecond. Here, we used the first three to create a custom date

from datetime import datetime
 
dt = datetime(2017, 12, 31)
 
print('Date and Time  = ', dt)

datetime function to create date and time

Date and Time = 2017-12-31 00:00:00

It is another example to create a custom date using the datetime function.

import datetime
 
dt = datetime.datetime(2018, 12, 31)
 
print('Date and Time  = ', dt)
 
dte = datetime.date(2018, 12, 31)
 
print('Date           = ', dte)

datetime function to create a custom date

Date and Time  =  2018-12-31 00:00:00
Date           =  2018-12-31

The first statement creates a custom date and time with zero hours. The second one creates a custom date and time, and the third one creates a custom date and time along with microseconds.

from datetime import datetime
 
dt = datetime(2014, 12, 31)
print('Date and Time  = ', dt)
 
dt2 = datetime(2014, 12, 31, 22, 33, 44)
print('Date and Time  = ', dt2)
 
dt3 = datetime(2016, 12, 31, 22, 33, 44, 123456)
print('Date and Time  = ', dt3)

datetime function to create custom date and time output.

Date and Time  =  2014-12-31 00:00:00
Date and Time  =  2014-12-31 22:33:44
Date and Time  =  2016-12-31 22:33:44.123456

Python timestamp function

The Python timestamp function returns the POSIX timestamp of the given datetime. Here, we are returning the timestamp of the current date and time.

from datetime import datetime
 
dt = datetime.now()
 
print('Today\'s Date   = ', dt)
print('Timestamp       = ', dt.timestamp())

datetime timestamp function output

Today's Date   =  2021-05-03 17:39:20.605253
Timestamp       =  1620043760.605253

Python utcfromtimestamp

The Python utcfromtimestamp method returns the UTC datetime from the given timestamp.

from datetime import datetime
 
tm_stamp = datetime.utcfromtimestamp(123456789)
print('Date  = ', tm_stamp)
 
tm_stamp2 = datetime.utcfromtimestamp(482056789)
print('Date  = ', tm_stamp2)
 
tm_stamp3 = datetime.utcfromtimestamp(19023456789)
print('Date  = ', tm_stamp3)
 
tm_stamp4 = datetime.utcfromtimestamp(12761456789)
print('Date  = ', tm_stamp4)

datetime utcfromtimestamp function output

Date  =  1973-11-29 21:33:09
Date  =  1985-04-11 08:39:49
Date  =  2572-10-29 21:33:09
Date  =  2374-05-25 01:06:29

Python datetime replace

The Python replace function replaces the date and time parts with new values. The syntax of this Python datetime replace is 

datetime.repalce(year = self.year, month = self.month, day = self.day, hour = self.hour, minute = self.minute, second = self.second, microsecond = self.microsecond, tzinfo = self.tzinfo)

We replaced hours, minutes, seconds, and microseconds from the current date and time.

from datetime import datetime
 
dt = datetime.now()
print('Date and Time = ', dt)
 
date_replace = dt.replace(hour = 2)
print('Date and Time = ', date_replace)
 
date_replace2 = dt.replace(minute = 59)
print('Date and Time = ', date_replace2)
 
date_replace3 = dt.replace(second = 4)
print('Date and Time = ', date_replace3)
 
date_replace4 = dt.replace(microsecond = 7)
print('Date and Time = ', date_replace4)

datetime replace function output

Date and Time =  2021-05-03 17:38:03.697423
Date and Time =  2021-05-03 02:38:03.697423
Date and Time =  2021-05-03 17:59:03.697423
Date and Time =  2021-05-03 17:38:04.697423
Date and Time =  2021-05-03 17:38:03.000007

The following are the list of all the other attributes and functions available in Python datetime class.

from datetime import datetime
 
dt = datetime.now()
print('Date and Time = ', dt)
 
print('Replace in Date = ', dt.replace(hour = 2))
print('Tzinfo from Date = ', dt.tzinfo)
print('Tzname from Date = ', dt.tzname())
 
print('Timetz from Date = ', dt.timetz())
print('Timestamp from Date = ', dt.timestamp())
print('Time from Date = ', dt.ctime())
print('isoweekday from Date = ', dt.isoweekday())
 
print('astimezone from Date = ', dt.astimezone())
print('utcoffset from Date = ', dt.utcoffset())
print('Daylight Saving from Date = ', dt.dst())
Date and Time =  2021-05-03 17:37:16.992139
Replace in Date =  2021-05-03 02:37:16.992139
Tzinfo from Date =  None
Tzname from Date =  None
Timetz from Date =  17:37:16.992139
Timestamp from Date =  1620043636.992139
Time from Date =  Mon May  3 17:37:16 2021
isoweekday from Date =  1
astimezone from Date =  2021-05-03 17:37:16.992139+05:30
utcoffset from Date =  None
Daylight Saving from Date =  None

Python datetime combine

The Python combine function returns a new datetime object by combining the given date value and time. The syntax of this Python combine is 

datetime.combine(date, time, tzinfo = self.tzinfo)

First, we declared a custom date and a custom time. Next, we used the Python combine function to combine those objects and return the date and time. From that date and time, we are returning date and time parts using the available attributes.

import datetime
 
dt = datetime.date(2018, 12, 31)
 
tm = datetime.time(23, 59, 58)
 
combine_dt = datetime.datetime.combine(dt, tm)
 
print('Date           = ', dt)
print('Time           = ', tm)
print('Date and Time  = ', combine_dt)
 
print('Year           = ', combine_dt.year)
print('Month          = ', combine_dt.month)
print('Day            = ', combine_dt.day)
print('Hour           = ', combine_dt.hour)
print('Minute         = ', combine_dt.minute)
print('Second         = ', combine_dt.second)
print('Microsecond    = ', combine_dt.microsecond)

datetime combine function output

Date           =  2018-12-31
Time           =  23:59:58
Date and Time  =  2018-12-31 23:59:58
Year           =  2018
Month          =  12
Day            =  31
Hour           =  23
Minute         =  59
Second         =  58
Microsecond    =  0

This example uses the combine function that combines the date and time. However, this time we are not providing the second’s value.

import datetime
 
dt = datetime.date(2018, 12, 31)
 
tm = datetime.time(23, 0)
 
combine_dt = datetime.datetime.combine(dt, tm)
 
print('Date           = ', dt)
print('Time           = ', tm)
print('Date and Time  = ', combine_dt)
Date           =  2018-12-31
Time           =  23:00:00
Date and Time  =  2018-12-31 23:00:00

Python datetime Date class

The Python datetime module has the date class used to manipulate or work with dates. We use the Python today method to return the current date.

from datetime import date
 
dt = date.today()
 
print('Today\'s Date  = ', dt)

datetime date today function output

Today's Date  =  2021-05-03

The Python date class in the datetime module has three important attributes. 

  • date.min: It returns the earliest or minimum representable date.
  • date.max: Latest or maximum representable date.
  • date.resolution: Smallest possible difference between continuous dates.
from datetime import date
 
print('Minimum Date         = ', date.min)
print('Maximum Date         = ', date.max)
print('Resolution           = ', date.resolution)

datetime date min, max, and resolution functions output

Minimum Date         =  0001-01-01
Maximum Date         =  9999-12-31
Resolution           =  1 day, 0:00:00

Python date class attributes

This example shows the list of date attributes available in python. Here, year attribute returns the year from the current date, month = month number, day = day of the month, and weekday = weekday

from datetime import date
 
dt = date.today()
 
print('Today\'s Date           = ', dt)
print('Year from Current Date  = ', dt.year)
print('Month from Current Date = ', dt.month)
print('Day from Current Date   = ', dt.day)
print('Weekday Number          = ', dt.weekday())

datetime date class attribute output

Today's Date           =  2021-05-03
Year from Current Date  =  2021
Month from Current Date =  5
Day from Current Date   =  3
Weekday Number          =  0

Create date using Python date

The date class in the datetime module has the date function to create a custom date from the year, month, and day of the month.

from datetime import date
 
dt = date(2018, 1, 31)
 
print('Date  = ', dt)

Creating Date using datetime date class output

Date = 2018-01-31

The Python fromtimestamp function accepts the POSIX timestamp value as an argument and returns the date from it.

from datetime import date
 
tm_stamp = date.fromtimestamp(123456789)
print('Date  = ', tm_stamp)
 
tm_stamp2 = date.fromtimestamp(412056789)
print('Date  = ', tm_stamp2)
 
tm_stamp3 = date.fromtimestamp(9123456789)
print('Date  = ', tm_stamp3)
 
tm_stamp4 = date.fromtimestamp(8761456789)
print('Date  = ', tm_stamp4)

datetime fromtimestamp function output

Date  =  1973-11-30
Date  =  1983-01-22
Date  =  2259-02-10
Date  =  2247-08-22

datetime Time class

The Python datetime module has the time class, which helps us to work with the time and manipulate them. This example uses the Python time method to return 00:00:00.

from datetime import time
 
tt = time()
print('Time  = ', tt)

datetime module time class output

Time = 00:00:00

The Python time class in the datetime module has the following 3 important attributes. 

  • time.min: It returns the earliest or minimum representable time.
  • time.max: Latest or maximum representable time.
  • time.resolution: Smallest possible difference between time.
from datetime import time
 
print('Minimum Time         = ', time.min)
print('Maximum Time         = ', time.max)
print('Resolution           = ', time.resolution)

Output of min, max, resolution functions in datetime time class

Minimum Time         =  00:00:00
Maximum Time         =  23:59:59.999999
Resolution           =  0:00:00.000001

Create Time using Python time

Here, we are using the time function to construct or create a time with 10 hours, 22 minutes, and 33 seconds

from datetime import time
 
tt = time(10, 22, 33)
print('Time  = ', tt)

datetime module time function output to create time

Time = 10:22:33

This Python time example is an extension of the above. Here, we are using the microseconds and the argument names as well.

from datetime import datetime, time
 
tme = datetime.time(datetime.now())
print('Current Time          = ', tme)
 
tt = time()
print('Time                  = ', tt)
 
tt1 = time(10, 22, 45)
print('Time                  = ', tt1)
 
tt2 = time(11, 34, 49, 890765)
print('Time                  = ', tt2)
 
tt3 = time(hour = 17, minute = 11, second = 33)
print('Time                  = ', tt3)
 
tt4 = time(hour = 17, minute = 22, second = 55, microsecond = 223344)
print('Time                  = ', tt4)

datetime time function output

Current Time          =  16:12:24.490551
Time                  =  00:00:00
Time                  =  10:22:45
Time                  =  11:34:49.890765
Time                  =  17:11:33
Time                  =  17:22:55.223344

Python time attributes

This example shows the list of available time attributes in python. Here, hour attribute returns the Hour from a given time, minute, second, and microsecond

from datetime import time
 
tt = time(10, 50, 33)
print('Time  = ', tt)
 
print('Hours        = ', tt.hour)
print('Minutes      = ', tt.minute)
print('Seconds      = ', tt.second)
print('Microseconds = ', tt.microsecond)

datetime time attributes output

Time  =  10:50:33
Hours        =  10
Minutes      =  50
Seconds      =  33
Microseconds =  0

Python date time timedelta

The datetime timedelta function predicts or return the past and future dates. In this example, we are returning the date and time after one year and two years before. Refer to Python timedelta.

from datetime import datetime, timedelta
 
dt = datetime.now()
 
print('Date and Time         = ', dt)
 
future_dt = dt + timedelta(days = 365)
print('Future Date and Time  = ', future_dt)
 
past_dt = dt - timedelta(days = 730)
print('Past Date and Time    = ', past_dt)

datetime timedelta function output

Date and Time         =  2021-05-03 16:10:47.540318
Future Date and Time  =  2022-05-03 16:10:47.540318
Past Date and Time    =  2019-05-04 16:10:47.540318

Python date time strftime

The datetime strftime function formats the date in the specified format, and return the date as a string. Here, %Y-%m-%d’ means Year-Month-Day (2019-01-31). Refer to Python strftime.

from datetime import datetime
 
dt = datetime.now()
print('Date and Time = ', dt)
 
dt2 = dt.strftime('%Y-%m-%d')
print('Date and Time = ', dt2)
 
dt3 = dt.strftime('%Y/%m/%d %H:%M:%S %p')
print('Date and Time = ', dt3)
 
dt4 = dt.strftime('%B %d, %Y %I-%M-%S %p')
print('Date and Time = ', dt4)

datetime strftime output

Date and Time =  2021-05-03 16:10:09.093105
Date and Time =  2021-05-03
Date and Time =  2021/05/03 16:10:09 PM
Date and Time =  May 03, 2021 04-10-09 PM

Python strptime

The datetime strptime converts the string representation of the date to a regular date and time. Here, datetime.strptime(dt_str, ‘%d %B %Y’) means string date is passes in Day Month_Name Year format. Refer Python strptime.

from datetime import datetime
 
dt_str = '31 December 2017'
dt_value = datetime.strptime(dt_str, '%d %B %Y')
print('Date and Time = ', dt_value)
 
dt_str2 = '15/8/17 22:33:55'
dt_value2 = datetime.strptime(dt_str2, '%d/%m/%y %H:%M:%S')
print('Date and Time = ', dt_value2)

datetime strptime output

Date and Time =  2017-12-31 00:00:00
Date and Time =  2017-08-15 22:33:55