How to use Python datetime to Create and use Dates and Times
Working with dates and times is a common task in Python. To help with this, Python has a native package called datetime
, which offers many different methods for creating and working with dates and times.
In this tutorial, we will learn how to use datetime
in Python using common examples that will be useful for real-world applications.
Import the datetime Package
Before the datetime
package can be used it will need to be imported at the top of your Python program like this:
import datetime
It is also possible to import methods of datetime
individually so they can be accessed more efficiently.
from datetime import datetime
from datetime import date
from datetime import time
Get Todays Date
To get today's date we can call the today()
method on the date object.
# Get Todays date
from datetime import date
date_today = date.today()
print(date_today)
2020-09-23
Get the Current Date and Time
To get the current date and time including milliseconds, use the datetime.now()
method.
# Get current Date and Time
datetime_obj = datetime.now()
print(datetime_obj)
2020-09-23 17:22:27.959933
Convert a String to a datetime Object
If you have a string that needs to be converted in a datetime
object, use the strptime()
method. Pass the string as the first argument and its format as the second and third (optional) arguments. If the format in the second/third argument does not correspond with the string, datetime
will not be able to interpret it and an error will be thrown.
# Convert a String to a datetime Object
from datetime import datetime
# %m/%d/%y %H:%M:%S Format
date_str_1 = '09/23/20, 23:53:06'
date_obj_1 = datetime.strptime(date_str_1, "%m/%d/%y, %H:%M:%S")
# d B Y format
date_str_2 = "24 September, 2020"
date_obj_2 = datetime.strptime(date_str_2, "%d %B, %Y")
print(date_obj_1)
print(date_obj_2)
2020-09-23 23:53:06
2020-09-24 00:00:00
Convert a datetime Object to a String
A command task is converting a datetime object to a string so that is can be printed or saved. This can be done using the strftime()
method. Pass date and time shorthand codes as the first argument inside ""
(double quotes), each with a leading %
(percent).
# formatting date to string with strftime()
from datetime import datetime
current = datetime.now()
# H:M:S Format
time = current.strftime("%H:%M:%S")
# m/d/Y Format
date_1 = current.strftime("%m/%d/%Y")
# %m/%d/%y %H:%M:%S Format
date_2 = current.strftime("%m/%d/%y, %H:%M:%S")
print(time)
print(date_1)
print(date_2)
23:53:06
09/23/2020
09/23/20, 23:53:06
Numerical Date Format Codes
Here are the numerical date format codes that can be used in a variety of different ways to get a date string in the format needed.
%Y
- year (2020)%y
- year (20)%m
- month (09)%d
- day (01)%H
- hour (14)%M
- minute (59)%S
- second (30)
Word Format Day and Month
Sometimes it is easier for humans to read dates with the day and month formatted in words. It is possible to do this by using different date format codes in conjunction with strftime()
.
# Word Format Week & Month
from datetime import datetime
current = datetime.now()
# %A, %d %B %Y Format
date_1 = current.strftime("%A, %d %B %Y")
# %A, %d %B %Y Format
date_2 = current.strftime("%a, %d %b %Y")
print(date_1)
print(date_2)
Thursday, 24 September 2020
Thu, 24 Sep 2020
%a
- abbreviated weekday name, (Sun, Mon .etc)%A
- full weekday name (Sunday, Monday .etc)%b
- abbreviated month name Jan, Feb, ..., Dec%B
- full month name January, February, ...
Convert a Timestamp to a Date
A Timestamp is the number of seconds since the Unix Epoch in 1970. To convert a timestamp into a date, use the fromttimestamp()
method on the date()
object.
# Timestamp to Date
from datetime import date
timestamp = date.fromtimestamp(1600949940)
print(timestamp)
2020-09-24
Print Current Day Month and Year
It is possible to get the current day month or year individually. They are available as properties on the date()
object.
# Print current day month and year
from datetime import date
# date object of today's date
today = date.today()
day = today.day
month = today.month
year = today.year
print(day)
print(month)
print(year)
24
9
2020
Format Times Using the time() Object
To format times, use the time() object and pass the hours, minutes, seconds and microseconds as arguments. It will create a new time()
object that can display the whole time. Parts of the time are available as properties of the time()
object and can be accessed individually.
# Format Time
from datetime import time
t = time(12, 4, 50)
print(t)
print(t.hour)
print(t.minute)
print(t.second)
print(t.microsecond)
12:04:50
12
4
50
0
Convert a datetime to a New Timezone
Handling the conversion of time zones can be challenging. The best option to keep things simple is to import a third-party package to do the nitty-gritty stuff for us. The best option is called pytz
. Let's import this package and examine how to convert a datetime()
date into a new timezone.
# Timezone Conversion
from datetime import datetime
import pytz
local = datetime.now()
tz_au = pytz.timezone('Australia/Sydney')
date_au = datetime.now(tz_au)
print('Local time (GMT):', local)
print('Time in Australia:', date_au)
Local time (GMT): 2020-09-24 15:06:09.287582
Time in Australia: 2020-09-25 00:06:09.287667+10:00
To print all of the timezones available in pytz
iterate through the all_timezones
property.
for tz in pytz.all_timezones:
print(tz)
Get the Difference Between Two Dates or Times
To get the difference between two date or times, create two date objects, subtract or add them together and store the result in a new variable. The new variable will be a timedelta()
object containing the difference between the dates. In the example below, we will find the difference between GMT and the time in Sydney, Australia (UTC+10).
# Timezone Difference
from datetime import datetime
import pytz
local = datetime.now()
tz_au = pytz.timezone('Australia/Sydney')
date_au = datetime.now(tz_au).replace(tzinfo=None)
difference = date_au - local
print('Local time (GMT):', local)
print('Time in Australia:', date_au)
print('Time Difference:', difference)
Local time (GMT): 2020-09-24 16:08:48.938236
Time in Australia: 2020-09-25 01:08:48.938319
Time Difference: 9:00:00.000083
note - the tzinfo
is removed from date_au
to make the date offset-unaware so it can be compared with local time.
Conclusion
You now know how to work with dates and times in Python including how to get different timezones and find the difference between dates.