Handle Date and Time in Python: datetime

Modified: | Tags: Python, Date and time

In Python, you can handle dates and times with the datetime module from the standard library.

The datetime module contains several classes. Be careful not to confuse the module and datetime class names, as they are both datetime.

  • datetime.datetime: Date and time
  • datetime.date: Date
  • datetime.time: Time
  • datetime.timedelta: Time difference or elapsed time

This article explains each class and the strftime() and strptime() methods used to convert date/time and strings.

For more details on processing ISO 8601 formatted strings and UNIX time (epoch seconds), see the following articles:

Additionally, the standard library includes the calendar module, which generates plain text and HTML calendars.

datetime objects

datetime objects store information about both the date (year, month, day) and time (hour, minute, second, microsecond). You can access this information using the year, month, day, hour, minute, second, and microsecond attributes.

datetime.now(): Today's date, current time

You can create a datetime object representing the current date and time with datetime.now().

Attributes such as year are stored as integers (int). This is true for attributes of date and time objects as well.

import datetime

dt_now = datetime.datetime.now()
print(dt_now)
# 2023-04-08 23:08:13.873520

print(type(dt_now))
# <class 'datetime.datetime'>

print(dt_now.year)
# 2023

print(type(dt_now.year))
# <class 'int'>

Constructor of datetime object

To create a datetime object for any date and time, use the constructor:

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

year, month, and day must be specified, while hour, minute, second, and microsecond are optional and default to 0 if not provided.

print(datetime.datetime(2023, 4, 1, 20, 15, 30, 2000))
# 2023-04-01 20:15:30.002000

print(datetime.datetime(2023, 4, 1))
# 2023-04-01 00:00:00

Create date and time objects from datetime object

You can convert a datetime object to a date object with the date() method and to a time object with the time() method.

dt = datetime.datetime(2023, 4, 1, 20, 15, 30, 2000)

d = dt.date()
print(d)
# 2023-04-01

print(type(d))
# <class 'datetime.date'>

t = dt.time()
print(t)
# 20:15:30.002000

print(type(t))
# <class 'datetime.time'>

Create datetime object from date and time objects

You can create a datetime object from date and time objects using datetime.combine().

print(datetime.datetime.combine(d, t))
# 2023-04-01 20:15:30.002000

date objects

date objects only store date information (year, month, and day). You can access this information using the year, month, and day attributes.

date.today(): Today's date

You can create a date object representing the current date (today's date) with date.today().

d_today = datetime.date.today()
print(d_today)
# 2023-04-08

print(type(d_today))
# <class 'datetime.date'>

print(d_today.month)
# 4

Constructor of date object

To create a date object for any date, use the constructor:

date(year, month, day)

All arguments are required and cannot be omitted.

print(datetime.date(2023, 4, 1))
# 2023-04-01

time objects

time objects only store time information (hour, minute, second, and microsecond). You can access this information using the hour, minute, second, and microsecond attributes.

Current time time object

As of Python 3.11, there is no direct method for creating a time object representing the current time. You can use datetime.now() to create a datetime object for the current date and time, and then convert it to a time object with the time() method.

t_now = datetime.datetime.now().time()
print(t_now)
# 23:08:13.919031

print(type(t_now))
# <class 'datetime.time'>

print(t_now.microsecond)
# 919031

Constructor of time object

To create a time object for any time, use the constructor:

time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

All arguments are optional and default to 0 if not provided.

print(datetime.time(20, 15, 30, 2000))
# 20:15:30.002000

print(datetime.time())
# 00:00:00

timedelta objects

timedelta objects represent the difference between two dates and times, which can be used to perform arithmetic with date, time, and datetime objects.

timedelta objects store information about days, seconds, and microseconds, which can be accessed with the days, seconds, and microseconds attributes. You can also get the total number of seconds (including microseconds) with the total_seconds() method as a floating point number (float).

Generate timedelta object by subtracting datetime, date objects

Subtracting one datetime object from another returns a timedelta object.

dt1 = datetime.datetime(2023, 4, 1, 20, 15, 30, 2000)
dt2 = datetime.datetime(2023, 7, 1, 10, 45, 15, 100)

td = dt2 - dt1
print(td)
# 90 days, 14:29:44.998100

print(type(td))
# <class 'datetime.timedelta'>

print(td.days)
# 90

print(td.seconds)
# 52184

print(td.microseconds)
# 998100

print(td.total_seconds())
# 7828184.9981

Subtracting one date object from another also returns a timedelta object.

Constructor of time object

The timedelta object constructor is as follows:

timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

All arguments are optional and default to 0 if not provided.

Note that the timedelta object only stores information on the number of days, seconds, and microseconds; for example, weeks=1 is equal to days=7.

td_1w = datetime.timedelta(weeks=1)
print(td_1w)
# 7 days, 0:00:00

print(td_1w.days)
# 7

Arithmetic with timedelta objects

You can perform arithmetic operations involving timedelta objects, date objects, and datetime objects. Adding or subtracting a timedelta object to/from a date or datetime object returns a new date or datetime object, respectively.

For example, you can easily calculate the date a week or 10 days in the future, or the time 50 minutes from now.

dt = datetime.datetime(2023, 4, 1, 20, 15, 30, 2000)
print(dt)
# 2023-04-01 20:15:30.002000

print(dt - datetime.timedelta(weeks=1))
# 2023-03-25 20:15:30.002000

print(dt + datetime.timedelta(days=10))
# 2023-04-11 20:15:30.002000

print(dt + datetime.timedelta(minutes=50))
# 2023-04-01 21:05:30.002000

It can also be used to calculate the number of days to a specific date.

d_target = datetime.date(2023, 5, 1)
td = d_target - dt.date()
print(td)
# 30 days, 0:00:00

print(td.days)
# 30

strftime(): Convert date and time to strings

The strftime() method converts datetime, date, and time objects into strings of any desired format.

Format codes

Refer to the official documentation for available format codes.

The main format codes are as follows:

  • %d: Day of the month as a zero-padded decimal number
  • %m: Month as a zero-padded decimal number
  • %y: Year without century as a zero-padded decimal number
  • %Y: Year with century as a decimal number
  • %H: Hour (24-hour clock) as a zero-padded decimal number
  • %I: Hour (12-hour clock) as a zero-padded decimal number
  • %M: Minute as a zero-padded decimal number
  • %S: Second as a zero-padded decimal number
  • %f: Microsecond as a decimal number, zero-padded to 6 digits
  • %A: Weekday as locale’s full name
  • %a: Weekday as locale’s abbreviated name
  • %B: Month as locale’s full name
  • %b: Month as locale’s abbreviated name
  • %j: Day of the year as a zero-padded decimal number
  • %U: Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number
  • %W: Week number of the year (Monday as the first day of the week) as a zero-padded decimal number

These format codes can also be used in the format string for the format() function and f-strings.

Additionally, dedicated methods are provided for ISO 8601 format strings.

Sample code

Here are some examples.

dt = datetime.datetime(2023, 4, 1, 20, 15, 30, 2000)
print(dt.strftime('%Y/%m/%d %H:%M:%S.%f'))
# 2023/04/01 20:15:30.002000

print(dt.strftime('%A, %B %d, %Y'))
# Saturday, April 01, 2023

The strftime() method can also be used with date and time objects. If you use time-related format codes with date objects or date-related format codes with time objects, it will not cause an error. Instead, the default values (such as 0 or 1) will be used.

d = dt.date()
print(d.strftime('%Y/%m/%d %H:%M:%S.%f'))
# 2023/04/01 00:00:00.000000

t = dt.time()
print(t.strftime('%Y/%m/%d %H:%M:%S.%f'))
# 1900/01/01 20:15:30.002000

For example, using a timedelta object, you can easily generate a list of dates at bi-weekly intervals in your desired format.

d = datetime.date(2023, 4, 1)
td = datetime.timedelta(weeks=2)
n = 4
f = '%Y/%m/%d'

l = [(d + i * td).strftime(f) for i in range(n)]
print(l)
# ['2023/04/01', '2023/04/15', '2023/04/29', '2023/05/13']

print('\n'.join(l))
# 2023/04/01
# 2023/04/15
# 2023/04/29
# 2023/05/13

strptime(): Convert strings to date and time

The strptime() method of the datetime class converts strings to datetime objects according to the specified format. The format string uses the same format codes as strftime().

Dedicated methods are also provided for ISO 8601 format strings (Python 3.7 and later). Refer to the following article.

Sample code

Specify the target string as the first argument and the format string as the second argument for strptime().

s = '2023/4/1 20:30'
s_format = '%Y/%m/%d %H:%M'
dt = datetime.datetime.strptime(s, s_format)
print(dt)
# 2023-04-01 20:30:00

print(type(dt))
# <class 'datetime.datetime'>

By using the strftime() method with the resulting datetime object, you can convert it into a string with a different format than the original.

print(dt.strftime('%Y%m%d_%H%M'))
# 20230401_2030

After converting a string to a datetime object, you can use a timedelta object to manipulate it, enabling operations like creating a date string representing a date 10 days ago in the same format.

s = '2023/4/1'
s_format = '%Y/%m/%d'
td_10d = datetime.timedelta(days=10)

dt = datetime.datetime.strptime(s, s_format) - td_10d
print(dt.strftime(s_format))
# 2023/03/22

Related Categories

Related Articles