mkaz.blog

Working with Dates

A set of examples working with Python date and time functions, including formatting dates, date calculations, and other common date tasks.

First off, all examples use the following import, any additional imports needed will be shown with the example.

from datetime import datetime

Creating Date Objects

Typically the first thing you want to do is create a Python date object, either from a known time, or parsing a string.

Create a Specific Date

# now
now = datetime.now()
 
# specific date
dt1 = datetime(2011, 8, 28)
dt2 = datetime(year=2012, month=3, day=2)

Create Date from Timestamp

Create a Python date object from a unix timestamp, a 10-digit number counting seconds from the epoch

ts = 1294204471
dt = datetime.fromtimestamp(ts)

Create Date from Known Format

Create Python date object from a string with a known format use strptime() see format table below for definitions.

str = "2012-10-20"
dts = datetime.strptime(str, '%Y-%m-%d')

Create Date from Unknown Format

To create a Python date object from a string with an unknown date format it is best to use the third-party dateutil module. Install using: python -m pip install python-dateutil

import dateutil.parser as parser
 
str1 = "October 11, 2018"
str2 = "Oct 11, 2018"
str3 = "Oct 11th, 2018"
parser.parse(str1)
parser.parse(str2)
parser.parse(str3)
 
# datetime.datetime(2018, 10, 11, 0, 0)

Date Format Table

Printing dates in various formats is relatively straight forward, here's one example. Refer to the table below for available formatting symbols and samples.

dt = datetime(2019, 8, 22)
dt.strftime("%b %d, %Y")
>>> 'Aug 22, 2019'
SymbolDefinitionExample
%aWeekday name abbreviatedSun, Mon, Tue, …
%AWeekday name fullSunday, Monday, Tuesday, …
%bMonth name abbreviatedJan, Feb, Mar, …
%BMonth name fullJanuary, February, …
%cA “random" date and time representation.Fri Jan 15 16:34:00 1999
%dDay of the month[ 01, 31 ]
%fMicrosecond[ 000000, 999999 ]
%HHour (24h)[ 00, 23 ]
%IHour (12h)[ 01, 12 ]
%jDay of the year[ 001, 366 ]
%mMonth[ 01, 12 ]
%MMinute[ 00, 59 ]
%pLocale's equivalent of either AM or PM.[ AM, PM ]
%SSecond[ 00, 61 ]
%UWeek number of the year (Sunday first)[ 00, 53 ]
%wWeekday number (Sunday=0)[ 0, 6 ]
%WWeek number of the year (Monday first)[0, 53 ]
%xLocale date01/15/99
%XLocale time16:34:00
%yYear without century[ 00, 99 ]
%YYear with century1999
%zUTC offset in the form +HHMM or -HHMM or empty
%ZTime zone name or empty string
%%A literal ‘%' character.

Format Date to RFC 2822

Use the formatdate() function from the email.utils built-in module.

For the current date and time:

from email.utils import formatdate
formatdate()
>>> 'Sat, 04 Mar 2023 04:36:44 -0000'

If you need a specific date to format, pass in a unix timestamp.

from email.utils import formatdate
dt = datetime(2020, 1, 25)
formatdate(dt.timestamp())
>>> 'Sat, 25 Jan 2020 08:00:00 -0000'

Date Calculations and Timedelta

from datetime import timedelta
 
week_later = dt + timedelta(days=7)
last_week = dt - timedelta(days=7)
in_five_minutes = dt + timedelta(minutes=5)

Valid timedelta properties are: weeks, days, hours, minutes, seconds, microseconds, milliseconds

You might notice that a “year" timedelta is absent, don't b tempted to do days=365, this would be off for leap-years. I would recommend something like the following:

st = datetime(year=2011, month=3, day=17)
next_year = datetime(year=st.year+1, month=st.month, day=st.day)

Adding and Subtracting Dates

You can add and subtract date objects when doing so they return timedelta objects. Using the timedelta object, you can access the same properties above.

dt1 = datetime(year=2012, month=8, day=23)
dt2 = datetime(year=2012, month=8, day=28)
td = dt2 - dt1
td.days
>>> 5

Convert Datetime to Date

To simplify a datetime to just the date, convert a datetime to date using .date() method:

dt = datetime.now()
dt
>>> datetime.datetime(2024, 3, 19, 5, 46, 17, 591196)
dt.date()
>>> datetime.date(2024, 3, 19)

Convert Date to Datetime

To add a time to a date, converting a date to datetime type use .combine() that merges a date object with a time object. Be careful with your imports that you use the datetime.time object.

from datetime import date
from datetime import datetime
from datetime import time as dt_time
 
dt = datetime.combine(date.today(), dt_time(0,0,0,0))

Common Date Functions

Here are examples of some commonly used Python date functions.

Yesterday

Use timedelta to create yesterday's date as a python date object.

from datetime import date, timedelta
yesterday = date.today() - timedelta(days=1)
yesterday.strftime('%Y-%m-%d')
>>> '2020-02-08'

Last Day of the Month

Two solutions, first using datetime and going to the first day of next month and subtracting a day.

from datetime import timedelta
now = datetime.now()
next_month = datetime(year=now.year, month=now.month+1, day=1)
last_day_month = next_month - timedelta(days=1)

Second solution to determine the last day of the month using the calendar module.

import calendar
now = datetime.now()
range = calendar.monthrange(now.year, now.month)
last_day_month = now.replace(day=range[1])

Next Thursday

today = datetime.now()
thursday_dow = 4
today_dow = first_day_of_month.strftime("%w")
adjustment = ( 7 + thursday_dow - int(today_dow)) % 7
next_thursday = today + timedelta(days=adjustment)

First Monday of the Month

today = datetime.now()
first_day_of_month = today.replace(day=1)
day_of_week = first_day_of_month.strftime("%w")
adjustment = (8 - int(day_of_week) ) % 7
first_monday = first_day_of_month + timedelta(days=adjustment)

Reference