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 | Explanation |
---|---|
%a | Weekday: Sun, Mon |
%A | Weekday: Sunday, Monday |
%w | Weekday: 0,1,2… |
%d | Day of month: 01,02 |
%b | Months: Jan, Feb |
%B | Months: January, February |
%m | Months: 01,02 |
%y | Year without century: 11,12,13 |
%Y | Year with century: 2011,2012 |
%H | 24 Hours clock: from 00 to 23 |
%I | 12 Hours clock: from 01 to 12 |
%p | AM, PM |
%M | Minute: 00 to 59 |
%S | Second: 00 to 59 |
%f | Microseconds: 6 decimal numbers |
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))
2022-12-10 11:13:06.693783
10.12.2022 11:13:06
12/10/2022 11:13:06
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)
2020-04-24 10:45:00