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 date
Code 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 31
Code 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()) # 1
Code 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:00
Code 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 + 1
Code 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:00
Code 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:
93
Code 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.000500
Code 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 500
Code 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.000500
Code 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-31
Code 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.000500
Code 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.000500
Code 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:
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)
Code language: Python (python)
Output:
December 12, 1999 09:30 AM
Code 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:00
Code 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 adate
, atime
, or adatetime
object. - Use the
strptime()
method to parse a string into adatetime
object.