DEV Community

Cover image for Python date & time conversion CheatSheet
Maiko Miyazaki
Maiko Miyazaki

Posted on • Edited on

Python date & time conversion CheatSheet

When dealing with data, we often find ourselves handling date and time. Although it is not particularly difficult, I often find myself googling the same conversion over and over again.

In this post, I'll share a cheat sheet of date and time conversion to eliminate such little time-consuming procedures and explain each technique in the following sections.

Open in PDF

Python date & time conversion CheatSheet

Table of Contents

1️⃣ String to DateTime object
2️⃣ DateTime object to String
3️⃣ String to String
4️⃣ UTC timestamp in seconds to DateTime object
5️⃣ UTC timestamp in seconds to String
6️⃣ UTC time string to UTC DateTime object in different GMT
7️⃣24-hour time String to 12-hour time String
7️⃣Download PDF file


String to DateTime object

Input Example: String "08/04/2021"
Output: Datetime object "2021-04-08 00:00:00"

We can use datetime.strptime to create a DateTime object from a string. strptime method takes two arguments -- target string and string to explain the format of the target string.

String to DateTime object

DateTime object to String

Input Example: DateTime object "2021-04-08 00:00:00"
Output: String "08/04/2021"

We can use datetime.strftimeto convert a DateTime object into String. This strftime method takes two arguments -- DateTime object and String to specify desired string format.

DateTime object to String

String to String

Input Example: String "08/04/2021"
Output: String "2021-04-08"

To convert datetime string into a different format of a string, we first need to convert it into a DateTime object. Then we can use strptimeto specify and convert into the desired format.

String to String

UTC timestamp in seconds to DateTime object

Input Example: float 1617836400.0 (UTC timestamp in seconds)
Output: DateTime object with "2021-04-08 00:00:00"

To convert float of timestamp into a DateTime, can use datetime.fromtimestamp(). It takes timestamp as an argument and returns DateTime object.

timestamp to DateTime object

UTC timestamp in seconds to String

Input Example: float 1617836400.0 (UTC timestamp in seconds)
Output: String "08/04/2021"

To convert float of timestamp into String, we first get a DateTime object. Using strftime method, we can then create desired format of String.

timestamp to String

UTC time string to UTC DateTime object in different GMT

Input Example: String "08-04-2021 08:33:00-0400" (New York timezone)
Output: DateTime object "2021-04-08 21:33:00+09:00" (Tokyo timezone)

To convert an UTC time string, we first convert it into a DateTime object. After that, we can use astimezone method to create a DateTime object in specified GMT.

UTC String to different UTC DateTime object

24-hour time String to 12-hour time String

Input Example: String "20:00"
Output: String "08:00 PM"

We first need to convert String into a DateTime object. Right after, 12-hour time string can be created using strftime method.

24-hour time String to 12-hour time String

Download PDF file

Open PDF


Thanks for reading. If you have any opinion or question, please leave a comment below! In the meantime, please follow me on Linkedin @Maiko Miyazaki or Twitter @Maiko Miyazaki

Top comments (6)

Collapse
 
shadowlion profile image
Justin Chiou

Really nice and clean! I would say the one thing to note for newbies who are using this - timestamp values are based on the number of seconds since epoch (January 01, 1970 UTC). I know it says the type is of timestamp, but one can forget to what order we base things off of - regardless, well done!

Collapse
 
maikomiyazaki profile image
Maiko Miyazaki

Thank you so much for pointing out Justin :) With your comment, I realized that I was not fully aware of the timestamp! As a result, I've managed to improve the article and PDF to clarify the values and types of the example. Thank you for taking your time to share it here! 😊🙏

Collapse
 
asanoaozora profile image
Philippe COLLIOT

Thank you Maiko San, this cheat sheet is very usefull. Just to share something I faced recently..
I wanted to get the timestamp from the time in a logcat file. The time was something like:
'00:00:11.493'
(the date was not significant for me)
In a first approach I did that:
dt = datetime.strptime('00:00:11.493', '%H:%M:%S.%f')
It seemed to be correct:
dt
datetime.datetime(1900, 1, 1, 0, 0, 11, 493000)

But I got an error
dt.timestamp()
Traceback (most recent call last):
File "<string>", line 1, in <module>
OSError: [Errno 22] Invalid argument

So I added a date
dt = datetime.strptime('01-01-2023 00:00:11.493', '%d-%m-%Y %H:%M:%S.%f')
dt
datetime.datetime(2023, 1, 1, 0, 0, 11, 493000)

And it worked
dt.timestamp()
1672527611.493

I investigated further and it appears something becomes wrong just before
dt = datetime.strptime('02-01-1970 01:00:00.000', '%d-%m-%Y %H:%M:%S.%f')

It seems to me that the default date (1900) is not consistent ?

Python 3.10.7
Windows 10 21H2

Collapse
 
maikomiyazaki profile image
Maiko Miyazaki

Hi Philippe, thanks for your comment!

I found this answer:

The reason why datetimes before 1970 may not work correctly on Windows systems is because of the way that Windows represents dates and times.

In Windows, dates and times are stored internally as the number of 100-nanosecond intervals that have elapsed since January 1, 1601, at 12:00:00 AM (UTC). This is known as the "Windows epoch".

However, many programming languages and libraries, including the popular C runtime library used by many Windows applications, use a different epoch known as the "Unix epoch", which is January 1, 1970, at 12:00:00 AM (UTC). This means that when working with dates and times in these languages and libraries, the values are typically calculated relative to the Unix epoch.

When a date before January 1, 1970, is used in a Windows system, the value calculated by subtracting the date from the Windows epoch is negative, which can lead to unexpected behavior and errors in some applications. This is because some programming languages and libraries may not handle negative values correctly, or may assume that all dates and times are relative to the Unix epoch.

To avoid these issues, it is important to be aware of the differences in epoch between Windows and Unix, and to use appropriate conversion functions or libraries when working with dates and times in Windows systems.

This conversation may help you to apply workaround: stackoverflow.com/questions/726604...

Collapse
 
aalphaindia profile image
Pawan Pawar

Good one!!

Collapse
 
maikomiyazaki profile image
Maiko Miyazaki

Thank you Pawan!