Python Datetime Format

Sharing is caring!

Last Updated on March 2, 2022 by Jay

The Datetime data can take many different forms and this is a reference/guide on the Python Datetime format.

Datetime formats are useful when we convert either from Datetime to String or vice versa.

Let’s create a datetime value:

import datetime
tdy = datetime.datetime.now()

print(tdy)
2022-03-02 00:43:41.710398

The datetime value above contains the year, month, day, hour, minute, second, and microsecond. The value has the following format: “%Y-%m-%d %H:%M:%S.%f”.

We can use the strftime(format) method to convert a datetime object into its string representation:

print(type(tdy))
<class 'datetime.datetime'>

tdy.strftime("%Y-%m-%d %H:%M:%S.%f")
'2022-03-02 00:43:41.710398'

Python Datetime Format Codes

DirectiveMeaningPossible ValuesExample
2022-03-02 00:43:41.710398
%aWeekday short nameSun, Mon, … , SatWed
%AWeekday full nameSunday, Monday, …, SaturdayWednesday
%wWeekday number0 (Sunday), 1 (Monday), …, 6 (Saturday)3
%dDay of month number01, 02, …, 3102
%bMonth short nameJan, Feb, …, DecMar
%BMonth full nameJanuary, February, …, DecemberMarch
%mMonth number01, 02, …, 1203
%yYear last two digits…, 19, 20, …, 22, …22
%YYear four digits…, 2019, 2020, …, 2022, …2022
%HHour 24 hr version00, 01, …, 2300
%IHour 12 hr version01, 02, …, 1212
%pAM/PMAM, PMAM
%MMinute number00, 01, …, 5943
%SSecond number00, 01, …, 5941
%fMicrosecond number000000, 000001, …, 999999710398
%jDay of year number001, 002, …, 365061
%UWeek number of the year (Sun first day of week)00, 01, …, 5309
%WWeek number of the year (Mon first day of week)09
%cLocal format for date and timeWed Mar 2 00:43:41 2022
%CCentury number first two digits…, 19, 20, …, 21, …20
%xLocal format for date03/02/22
%XLocal format for time00:43:41
%%A literal % character%%

Additional Resources

How to Convert Column to Datetime in Pandas

How to Convert Datetime to String in Pandas

How to Filter Pandas Dataframe by Date

2 comments

  1. Hi, do you have an article on how to convert an excel data type, for example, a number saved as text to convert to text and save an excel file?

Leave a Reply

Your email address will not be published. Required fields are marked *