Python datetime

Summary: in this tutorial, you’ll learn how to use the Python datetime module to manipulate dates and times.

Introduction to the Python datetime module

The datetime is a built-in module that provides classes for manipulating dates and times.

To manipulate dates, you use the date class. For example, the following example creates a new date object with year, month, and day:

from datetime import date

d = date(1999, 12, 31)
print(d)
print(type(d))Code language: Python (python)

Output:

1999-12-31
<class 'datetime.date'>Code language: Python (python)

How it works.

First, import the date class from the datetime module:

from datetime import dateCode language: Python (python)

Second, create a new date object with three integers year, month, and day:

d = date(1999, 12, 31)Code language: Python (python)

Note that if you use integers that are not valid for years, months, and days, you’ll get a ValueError exception.

Third, display the date object and its type:

1999-12-31
<class 'datetime.date'>Code language: Python (python)

Getting the year, month, and day of a date object

A date object has some useful properties such as year, day, and month:

from datetime import date

d = date(1999, 12, 31)
print(d.year, d.month, d.day)Code language: Python (python)

Output:

1999 12 31Code language: Python (python)

Getting the current date

To get the current date, you use the today() class method:

from datetime import date

d = date.today()
print(d)Code language: Python (python)

Getting the weekday

The weekday() returns the day of the week where Monday is zero, Tuesday is one, and so on. The isoweekday() also returns the day of the week but Monday is one, Tuesday is two, and so on. For example:

from datetime import date

d = date(1999, 12, 31)

print(d.weekday())
print(d.isoweekday())Code language: Python (python)

To get the day name based on a weekday, you can use the day_name() function of the calendar module. For example:

import calendar
from datetime import date

d = date(1999, 12, 27)

print(calendar.day_name[d.weekday()])  # Monday

print(d.weekday())  # 0
print(d.isoweekday())  # 1Code language: Python (python)

timedelta

To represent the difference between two dates, you use the timedelta class. The following creates a new timedelta object:

from datetime import timedelta

delta = timedelta(days=7)
print(delta)Code language: Python (python)

Output:

7 days, 0:00:00Code language: CSS (css)

Once having a timedelta object, you can add/subtract it to/from a date object. For example, the following uses a timedelta to add 7 days to a today date:

from datetime import timedelta, date


delta = timedelta(days=7)
next_week = date.today() + delta
print(next_week)Code language: Python (python)

Adding/subtracting two dates

When you add or subtract two dates, you’ll get a timedelta object. For example, the following shows the number of days to the new year:

from datetime import date

next_year = date.today().year + 1
new_year = date(next_year, 1, 1)
day_to_new_year = new_year - date.today()

print(type(day_to_new_year))
print(day_to_new_year)Code language: Python (python)

How it works.

First, get the new year by adding one to the current year from today’s date:

next_year = date.today().year + 1Code language: Python (python)

Second, create a new date object with the new year date:

new_year = date(next_year, 1, 1)Code language: Python (python)

Third, subtract today’s date from the new year:

day_to_new_year = new_year - date.today()Code language: Python (python)

Finally, show the output:

print(type(day_to_new_year))
print(day_to_new_year)Code language: Python (python)

Output:

<class 'datetime.timedelta'>
93 days, 0:00:00Code language: Python (python)

Note that the number of days when you run the program is likely different.

To get the number of days only from a timedelta, you use the days property:

from datetime import date

next_year = date.today().year + 1
new_year = date(next_year, 1, 1)
day_to_new_year = new_year - date.today()

print(day_to_new_year.days)Code language: Python (python)

Output:

93Code language: Python (python)

Time

To represent times, you use the time class from the datetime module. For example, the following creates a new time object with hour, minute, second, and microsecond:

from datetime import time


t = time(9, 30, 45, 500)
print(t)Code language: Python (python)

Output:

09:30:45.000500Code language: Python (python)

Like a date object, the time object has the hour, minute, second, and microsecond properties:

from datetime import time


t = time(9, 30, 45, 500)
print(t.hour, t.minute, t.second, t.microsecond)Code language: Python (python)

Output:

9 30 45 500Code language: Python (python)

datetime

The datetime class represents both dates and times. The following creates a new datetime object with the year, month, day, hour, minute, second, and microsecond:

from datetime import datetime


dt = datetime(1999, 12, 31, 9, 30, 45, 500)
print(dt.date())Code language: Python (python)

Output:

1999-12-31 09:30:45.000500Code language: Python (python)

To get the current time, you use the now() method of the datetime() object:

from datetime import datetime, timedelta


current_time = datetime.now()
print(current_time)Code language: Python (python)

To get a date object out of the datetime object, you use the date() method:

from datetime import datetime


dt = datetime(1999, 12, 31, 9, 30, 45, 500)
print(dt.date())Code language: Python (python)

Output:

1999-12-31Code language: Python (python)

Similarly, the time() method returns the time object of the datetime object:

from datetime import datetime


dt = datetime(1999, 12, 31, 9, 30, 45, 500)
print(dt.time())Code language: Python (python)

Output:

09:30:45.000500Code language: Python (python)

Like date and time objects, you can add/subtract a timedelta to/from a datetime object. For example:

from datetime import datetime


current_time = datetime.now()
print(current_time)Code language: Python (python)

Output:

2000-01-01 14:30:45.000500Code language: Python (python)

In this example, we add 1 day and 5 hours to a datetime object.

To get the current in UTC, you use the utcnow() method:

from datetime import datetime


current_time = datetime.utcnow()
print(current_time)Code language: Python (python)

Formatting dates & times

The date, time, and datetime objects have the strftime() method that formats date, time, and datetime. It accepts an argument (format):

strftime(format)Code language: Python (python)

The format argument contains directives for formatting dates and times. The following table shows the format directives:

DirectiveMeaningExample
%aAn abbreviated weekday nameMon, Tue
%AA Full weekday nameMonday, Tuesday, …
%wA Weekday (0 is Sunday and 6 is Saturday)0, 1, …, 6
%dA zero-padded day of the month01, 02, …, 31
%bAn abbreviated month nameJan, Feb, …
%BA full month nameJanuary, February…
%mA zero-padded month01, 02, …, 12
%yA zero-padded year without century00, 01, …, 99
%YA zero-padded year with century0001, 1999, …
%HA zero-padded hour in a 24-hour clock00, 01, …, 23
%IA zero-padded hour in a 12-hour clock01, 02, …, 12
%pAM or PMAM, PM
%Ma zero-padded minute00, 01, …, 59
%Sa zero-padded second00, 01, …, 59
%fa zero-padded to 6 digits of microsecond000000, 000001, …, 999999
%zUTC offset in the form ±HHMM[SS[.ffffff]]-0400, +1030, …
%ZTime zone nameUTC, GMT, ”
%jThe zero-padded day of the year001, 002, …, 366
%UWeek number of the year00, 01, …, 53
%WWeek number of the year00, 01, …, 53
%cdate and time representation.Fri Dec 31 09:30:45 1999
%xDate string12/31/99
%XTime string09:30:45
%%The literal '%' character.%

For example, the following shows how to use the strftime() method to format a date time:

from datetime import datetime


dt = datetime(1999, 12, 31, 9, 30, 45)
s = dt.strftime('%B %m, %Y %I:%M %p')
print(s)Code language: Python (python)

Output:

December 12, 1999 09:30 AMCode language: Python (python)

Convert a string to date & time

The strptime() is a class method of the datetime class, which parses a string with a given format to a datetime object:

strptime(date_string, format)

For example:

from datetime import datetime


dt = datetime.strptime('August 13, 2022', '%B %d, %Y')
print(dt)
Code language: JavaScript (javascript)

Output:

2022-08-13 00:00:00Code language: CSS (css)

Summary

  • Use the date class to represent dates.
  • Use the time class to represent times.
  • Use the datetime class to represent both dates and times.
  • Use the timedelta class to represent a time delta.
  • Use the strftime() method to format a date, a time, or a datetime object.
  • Use the strptime() method to parse a string into a datetime object.
Did you find this tutorial helpful ?