The syntax of strftime() method is...
dateobject.strftime(format)
Where format is the desired format of date string that user wants. Format is built using codes shown in the table below...
Code | Meaning |
---|---|
%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 |
%p | AM, PM |
%M | Minutes from 00 to 59 |
%S | Seconds from 00 to 59 |
%f | Microseconds 6 decimal numbers |
Example: Convert current time to date string...
import datetime
from datetime import datetime
now = datetime.now()
print(now)
Let us convert the above datetime object to datetime string now.
now.strftime("%Y-%m-%d %H:%M:%S")
If you want to print month as locale’s abbreviated name, replace %m with %b as shown below...
now.strftime("%Y-%b-%d %H:%M:%S")
Another example...
now.strftime("%Y/%b/%A %H:%M:%S")
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)
Let us convert the above date object to Python date string using strftime().
today.strftime("%Y-%m-%d %H:%M:%S")
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")
example:
strptime("9/23/20", "%d/%m/%y")
Note - format "%d/%m/%y" represents the the corresponding "9/23/20" format. The output of the above command will be a Python datetime object.
The format is constructed using pre-defined codes. There are many codes to choose from. The most important ones are listed below.
Code | Meaning |
---|---|
%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 |
%p | AM, PM |
%M | Minutes from 00 to 59 |
%S | Seconds from 00 to 59 |
%f | Microseconds 6 decimal numbers |
Example: Convert date string to Python datetime object.
import datetime
datetime.datetime.strptime("09/23/2030 8:28","%m/%d/%Y %H:%M")
Related Notebooks
- String And Literal In Python 3
- Summarising Aggregating and Grouping data in Python Pandas
- Merge and Join DataFrames with Pandas in Python
- Write Single And Multi Line Comments In Python
- How To Code RNN and LSTM Neural Networks in Python
- Python Iterators And Generators
- Python Sort And Sorted
- Remove An Item From A List In Python Using Clear Pop Remove And Del
- Learn And Code Confusion Matrix With Python