In this post, we will learn about strftime() method from Python datetime package.
The strftime converts date object to a string date.
Python Strftime Format
The syntax of strftime() method is...
Where format is the desired format of date string that user wants. Format is built using codes shown in the table below...
|%a||Weekday as Sun, Mon|
|%A||Weekday as full name as Sunday, Monday|
|%w||Weekday as decimal no as 0,1,2...|
|%d||Day of month as 01,02|
|%b||Months as Jan, Feb|
|%B||Months as January, February|
|%m||Months as 01,02|
|%y||Year without century as 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|
|%M||Minutes from 00 to 59|
|%S||Seconds from 00 to 59|
|%f||Microseconds 6 decimal numbers|
Datetime To String Python
Example: Convert current time to date string...
import datetime from datetime import datetime now = datetime.now() print(now)
datetime.datetime(2020, 9, 22, 3, 20, 22, 255262)
Let us convert the above datetime object to datetime string now.
The output of above command will be...
If you want to print month as locale’s abbreviated name, replace %m with %b as shown below...
You should see this ...
If you just want to extract the date and ignore time, then do following...
Output of above should be...
Date To String Python
Date to string is quite similar to datetime to string Python conversion.
Example: Convert current date object to Python date string.
today = datetime.today() print(today)
datetime.datetime(2020, 9, 22, 3, 50, 1, 268575)
Let us convert the above date object to Python date string using strftime().
output of above command...
Python Strftime Milliseconds
To get a date string with milliseconds, use %f format code at the end as shown below..
today = datetime.today() today.strftime("%Y-%m-%d %H:%M:%S.%f")
You should see following output...