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
Directive | Meaning | Possible Values | Example 2022-03-02 00:43:41.710398 |
%a | Weekday short name | Sun, Mon, … , Sat | Wed |
%A | Weekday full name | Sunday, Monday, …, Saturday | Wednesday |
%w | Weekday number | 0 (Sunday), 1 (Monday), …, 6 (Saturday) | 3 |
%d | Day of month number | 01, 02, …, 31 | 02 |
%b | Month short name | Jan, Feb, …, Dec | Mar |
%B | Month full name | January, February, …, December | March |
%m | Month number | 01, 02, …, 12 | 03 |
%y | Year last two digits | …, 19, 20, …, 22, … | 22 |
%Y | Year four digits | …, 2019, 2020, …, 2022, … | 2022 |
%H | Hour 24 hr version | 00, 01, …, 23 | 00 |
%I | Hour 12 hr version | 01, 02, …, 12 | 12 |
%p | AM/PM | AM, PM | AM |
%M | Minute number | 00, 01, …, 59 | 43 |
%S | Second number | 00, 01, …, 59 | 41 |
%f | Microsecond number | 000000, 000001, …, 999999 | 710398 |
%j | Day of year number | 001, 002, …, 365 | 061 |
%U | Week number of the year (Sun first day of week) | 00, 01, …, 53 | 09 |
%W | Week number of the year (Mon first day of week) | 09 | |
%c | Local format for date and time | Wed Mar 2 00:43:41 2022 | |
%C | Century number first two digits | …, 19, 20, …, 21, … | 20 |
%x | Local format for date | 03/02/22 | |
%X | Local format for time | 00:43:41 | |
%% | A literal % character | % | % |
Additional Resources
How to Convert Column to Datetime in Pandas
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?
Hi Viktor,
For converting between numbers and text data, you can simply cast the data column to a specified data type. For example,
df['a'].astype(str)
This tutorial might contain what you are looking for:
https://pythoninoffice.com/convert-text-string-to-number-in-pandas
Hope that helps, let me know if you have other questions!
Jay