Datetime

Datetime#

This page describes Python features for working with date and time objects. Check the relevant page in the documentation.

from datetime import date, time, datetime

String conversions#

It turns out that it’s quite typical to transform strings to datetime data types and vice versa, so this question deserves separate consideration. Check corresponding section in official documentation.

Use datetime.strptime to convert string to date and the strftime method of datetime.date, datetime.time, or datetime.datetime objects.

You must specify a format string that indicates the format to convert to or convert from. You can specify different components of date or time (such as days, hours, etc.) using special symbols that begin with the % symbol. Look for a full list of possible components in the corresponding section of the official documentation.


Consider some examples of format strings. The following cell prints outputs for a set of format strings for typical formats used in different contexts.

obj = datetime(2000, 10, 20, 12, 33, 17, 3333)
formats = [
    "%Y-%m-%d %H-%M-%S.%f",
    "%d.%m.%Y",
    "%Y/%d/%m"
]

for format in formats:
    print(format + " -> " + obj.strftime(format))
%Y-%m-%d %H-%M-%S.%f -> 2000-10-20 12-33-17.003333
%d.%m.%Y -> 20.10.2000
%Y/%d/%m -> 2000/20/10

An example of conversion from string to datetime: the same string with different format strings produces different datetime objects.

datetime.strptime("2000-10-12", "%Y-%m-%d"),\
datetime.strptime("2000-10-12", "%Y-%d-%m")
(datetime.datetime(2000, 10, 12, 0, 0), datetime.datetime(2000, 12, 10, 0, 0))