Working with strings

Python provides two useful functions to work with time strings with strftime() and strptime() from the datetime standard library.

With the strftime() function (string from time) you can create simple strings from date, datetime and time objects. It only needs a so-called format string, which describes what should be contained in the time string.

The strptime() functino in python is used to convert string to datetime object.

Code Formatting

CodeExplanation
%aWeekday: Sun, Mon
%AWeekday: Sunday, Monday
%wWeekday: 0,1,2…
%dDay of month: 01,02
%bMonths: Jan, Feb
%BMonths: January, February
%mMonths: 01,02
%yYear without century: 11,12,13
%YYear with century: 2011,2012
%H24 Hours clock: from 00 to 23
%I12 Hours clock: from 01 to 12
%pAM, PM
%MMinute: 00 to 59
%SSecond: 00 to 59
%fMicroseconds: 6 decimal numbers

Example 1: strftime() – date to string

import datetime

dateFormatDE = "%d.%m.%Y %H:%M:%S"
dateFormatEN = "%m/%d/%Y %H:%M:%S"
dt = datetime.datetime.now()

print(dt)
print(dt.strftime(dateFormatDE))
print(dt.strftime(dateFormatEN))
Output
2022-12-10 11:13:06.693783
10.12.2022 11:13:06
12/10/2022 11:13:06

Example 2: strptime() – string to date

Here we convert a date in string format to a datetime object.

import datetime

dateString = "04/24/2020 10:45"
dt = datetime.datetime.strptime(dateString, "%m/%d/%Y %H:%M")

print(dt)
Output
2020-04-24 10:45:00