Python Datetime

Dictionary List Set Tuple Array Class Compression Console Convert Datetime Def Exception File Generator If Itertools JIT Lambda Loop Map Math None Number Path Print Re Slice Sort Split String Urllib


Space and time are connected. But in Python scripts, we are concerned most with simpler aspects of time. With the datetime module, we parse strings containing dates. And we can manipulate time spans.

Tip:Built-in date time libraries are available.
They make many programs much easier to write.

Based on:

Python 3.2.4



It is often tricky to parse dates from strings. In Python, we have the strptime method in datetime. The name is confusing. It is best just to memorize it. This method requires two arguments.

Arguments:The first argument is a string containing date information. The second argument is the format string.

Format codes

B: The full month name.
d: The digit of the day of the month.
Y: The four-digit year.

Program that uses strptime: Python

from datetime import datetime

# Input string.
s = "August 16, 2012"

# Use strptime.
d = datetime.strptime(s, "%B %d, %Y")


2012-08-16 00:00:00


Shift operator

Yesterday is always the current date minus one day. In Python we compute this with timedelta. This type resides in the datetime module. We introduce a method called yesterday(). It calls today() and then subtracts a timedelta of 1 day.

Tip:A timedelta can be subtracted or added to a date object. In this way, we compute yesterday, today and any other relative day.

Program that returns yesterday: Python

from datetime import date
from datetime import timedelta

def yesterday():
    # Get today.
    today =

    # Subtract timedelta of 1 day.
    yesterday = today - timedelta(days=1)
    return yesterday






Tomorrow is computed in the same way as yesterday. We add a timedelta of one day to the current day. This version uses a shorter syntax form. It reduces the number of steps in the method body.

Info:Helper methods, such as tomorrow and yesterday, are a useful abstraction in certain programs. They are reusable.

Program that gets tomorrow: Python

from datetime import date
from datetime import timedelta

def tomorrow():
    # Add one day delta.
    return + timedelta(days=1)




Sort dates

Sorted letters: A to Z

A list of dates can be sorted. Suppose your Python program has a list of dates and they are unordered. Often we will need to order them chronologically, from first to last (or in reverse). We can sort dates like any other type.

Here:We create a list and append four new dates to it.
These are all dates in the future.
They are not chronologically ordered.


Then:We invoke the sort method on the list. In a for-loop, we display the dates, now ordered from first to last in time.

Program that sorts date list: Python

from datetime import date, timedelta

# Create a list of dates.
values = []
values.append( + timedelta(days=300))
values.append( + timedelta(days=2))
values.append( + timedelta(days=1))
values.append( + timedelta(days=20))

# Sort the list.

# Display.
for d in values:




Not equal

No two points in time are the same. In Python we express the difference between two dates with timedelta. To use timedelta, provide the arguments using names. And not all units are supported—we cannot specify years.

Here:In this program, we subtract one hour from one day. And, as you might expect, the result is 23 hours.

Program that uses timedelta: Python

from datetime import timedelta

# This represents 1 day.
a = timedelta(days=1)

# Represents 1 hour.
b = timedelta(hours=1)

# Subtract 1 hour from 1 day.
c = a - b


Python language

Next, we consider the possible arguments to timedelta in more detail. You can specify more than argument to timedelta—simply use a comma to separate them.
Large units like years,
and small units,
like nanoseconds,
are not included.

Timedelta arguments
    (From smallest to largest)


File timestamps

Time: moments in time

This program uses the os.path module as well as the date module.
It gets the access,
and creation of time of a file. You will need to change the file name to one that exists on your disk. The returned values are timestamps.


But:In many programs we prefer a date type, not a float type. Dates are easier to understand and print.

So:We use the fromtimestamp method from the date module. This converts, correctly, the floats to dates.

I verified that the three dates are correct in this program according to Windows 8.1. The file creation time is later than the modification time because the file was copied. Getctime on some platforms returns a different value.

Program that gets timestamps, converts to dates: Python

from os import path
from datetime import date

# Get access, modification, and creation time.
a = path.getatime("/enable1.txt")
m = path.getmtime("/enable1.txt")
c = path.getctime("/enable1.txt")

# Display the times.
print(a, m, c)

# Convert timestamps to dates.
a2 = date.fromtimestamp(a)
m2 = date.fromtimestamp(m)
c2 = date.fromtimestamp(c)
print(a2, m2, c2)

Output, format edited

1360539846.3326 1326137807.9652 1360539846.3326
2013-02-10      2012-01-09      2013-02-10



Getting the date,
as with,
is slow. This call must access the operating system. An easy way to optimize this is to cache dates. If your program must access today(), avoid this call in a tight loop.


Loop 1:This loop access once on each iteration through the loop. It runs much slower.

Loop 2:The call is cached in a variable before the loop runs. This makes each iteration much faster. We hoist the call.

Also:The logic checks the year of the date.
This can be changed for the current year.

Program that caches date: Python

import time
from datetime import date

# Time 1

# Accesses today repeatedly.
i = 0
while i < 100000:
    t =
    if t.year != 2013:
        raise Exception()
    i += 1

# Time 2

# Accesses today once.
i = 0
t =
while i < 100000:
    if t.year != 2013:
        raise Exception()
    i += 1

# Time 3


1361485333.411    Loop 1 = 0.173
1361485333.435    Loop 2 = 0.024



The Python language provides strong support for time handling. These libraries are built into the environment. They do not need to be recreated in each program. This yields faster, more reliable software.

Tip:Certain aspects of time handling, such as computing calendar dates by offsets, is best left to sophisticated libraries.

And:Developing custom libraries is challenging. Many possible problems must be handled—even leap years.