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))Output:
1999-12-31
<class 'datetime.date'>How it works.
First, import the date class from the datetime module:
from datetime import dateSecond, create a new date object with three integers year, month, and day:
d = date(1999, 12, 31)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'>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)Output:
1999 12 31Getting the current date #
To get the current date, you use the today() class method:
from datetime import date
d = date.today()
print(d)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())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()) # 1timedelta #
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)Output:
7 days, 0:00:00Once 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)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)How it works.
First, get the new year by adding one to the current year from today’s date:
next_year = date.today().year + 1Second, create a new date object with the new year date:
new_year = date(next_year, 1, 1)Third, subtract today’s date from the new year:
day_to_new_year = new_year - date.today()Finally, show the output:
print(type(day_to_new_year))
print(day_to_new_year)Output:
<class 'datetime.timedelta'>
93 days, 0:00:00Note 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)Output:
93Time #
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)Output:
09:30:45.000500Like 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)Output:
9 30 45 500datetime #
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())Output:
1999-12-31 09:30:45.000500To 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)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())Output:
1999-12-31Similarly, 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())Output:
09:30:45.000500Like 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)Output:
2000-01-01 14:30:45.000500In 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)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)The format argument contains directives for formatting dates and times. The following table shows the format directives:
| Directive | Meaning | Example |
|---|---|---|
%a | An abbreviated weekday name | Mon, Tue |
%A | A Full weekday name | Monday, Tuesday, … |
%w | A Weekday (0 is Sunday and 6 is Saturday) | 0, 1, …, 6 |
%d | A zero-padded day of the month | 01, 02, …, 31 |
%b | An abbreviated month name | Jan, Feb, … |
%B | A full month name | January, February… |
%m | A zero-padded month | 01, 02, …, 12 |
%y | A zero-padded year without century | 00, 01, …, 99 |
%Y | A zero-padded year with century | 0001, 1999, … |
%H | A zero-padded hour in a 24-hour clock | 00, 01, …, 23 |
%I | A zero-padded hour in a 12-hour clock | 01, 02, …, 12 |
%p | AM or PM | AM, PM |
%M | a zero-padded minute | 00, 01, …, 59 |
%S | a zero-padded second | 00, 01, …, 59 |
%f | a zero-padded to 6 digits of microsecond | 000000, 000001, …, 999999 |
%z | UTC offset in the form ±HHMM[SS[.ffffff]] | -0400, +1030, … |
%Z | Time zone name | UTC, GMT, ” |
%j | The zero-padded day of the year | 001, 002, …, 366 |
%U | Week number of the year | 00, 01, …, 53 |
%W | Week number of the year | 00, 01, …, 53 |
%c | date and time representation. | Fri Dec 31 09:30:45 1999 |
%x | Date string | 12/31/99 |
%X | Time string | 09: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)Output:
December 12, 1999 09:30 AMConvert 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)Output:
2022-08-13 00:00:00Summary #
- Use the
dateclass to represent dates. - Use the
timeclass to represent times. - Use the
datetimeclass to represent both dates and times. - Use the
timedeltaclass to represent a time delta. - Use the
strftime()method to format adate, atime, or adatetimeobject. - Use the
strptime()method to parse a string into adatetimeobject.
Thank you for your feedback!