Dates and times

Use the datetime library to work with dates and times in Python.

Import the library to get started…

from datetime import datetime

To create a datetime object for a given date and time.

  • Example date & time: 29 July 2021, 7:08pm.
# -- Method 1 -- Create from integers
d = datetime(2021, 7, 29, 19, 8, 0)

# -- Method 2 -- Create from parsing a string
d = datetime.strptime("29/07/2021 19:08:00", "%d/%m/%Y %H:%M:%S")

To create a datetime object for the current time

now1 = datetime.now()               # Local time
now2 = datetime.utcnow()            # UTC time

Creating strings to display dates and times

s1 = d.strftime("%A %d %B, %Y")     # Thursday 29 July, 2021
s2 = d.strftime("%I:%M %p")         # 7:08 pm
print(s1, s2)

Computers commonly use midnight 1 January 1970 as an “epoch” (beginning point) for time calculations. If you are working with time or date information generated by other programs, you may have to convert to/from this format. It is an integer that is the number of seconds that have elapsed since that moment, 1/1/1970 00:00:00 UTC.

Convert to/from an epoch timestamp

timestamp = datetime.timestamp(my_date)       # 1627556880.0
my_date = datetime.fromtimestamp(timestamp)

# Get current epoch timestamp - Method 1
timestamp = datetime.now().timestamp()        # 1625564993.5

# Get current epoch timestamp - Method 2 -- using time library
import time
timestamp = time.time()                       # 1625564993.5

  To find the difference between two dates, import timedelta as well.

from datetime import datetime, timedelta

# Difference between two dates
past_date  = datetime(1969, 7, 20, 20, 17, 40)
difference = datetime.now() - past_date
print( difference.days )

# What is/was the date 1000 days from now?
now = datetime.now()
past_date = now - timedelta(days=1000)  
future_date = now + timedelta(days=1000)

Codes for datetime strings

  • These are the codes to parse date strings when using strptime() and strftime()
%a   Thu       day
%A   Thursday  day
%d   29        day number
%m   07        month
%b   Jul       month
%B   July      month
%y   21        year
%Y   2021      year
%I   7         hour 12h
%H   19        hour 24h
%M   08        minute
%S   00        second
%p   PM        AM/PM

Copyright © Paul Baumgarten.