Dates

Python has a built-in module called datetime that can be used to create and modify datetime objects.

Because the module comes built-in with Python, installation is not required, but we do need to import it at top of a Python file.

As an example, the code below employs the .datetime.now() method to return the current date and time:

The result will be the current date and time, something like:

2022-10-05 10:20:57.944968

It contains the year, month, day, hour, minute, second, and microsecond:

YYYY-MM-DD hh:mm:ss.ffffff

Creating New datetime Objects

The datetime module has three main types available:

  • date
  • time
  • datetime
import datetime
# Create date object with year=2021, month=10, and day=5
meeting_date = datetime.date(2021, 10, 5)
# Create time object with hour=10, minute=5, and seconds=31
meeting_time = datetime.time(10, 5, 31)
# Create datetime object with year=2021, month=10, day=5, hour=10, minute=5 and seconds=31
meeting = datetime.datetime(2021, 10, 5, 10, 5, 31)

Furthermore, we also have a timedelta type which is used to represent time difference.

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

Note that all of the arguments are optional and have default value of 0.

Operations on datetime Objects

We can perform different operations on a datetime object. For example, if we want to add 2 months to a current date, it can be done as below:

Date and time differences can be calculated using the subtraction operator - on datetime objects.

Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn Python on Codecademy