DEV Community

Code_Jedi
Code_Jedi

Posted on

4 2

How to Convert Unix Time to Datetime and Vice Versa in Python

Unix timestamps are unreadable to humans, Datetimes are unreadable to machines. Time often needs to converted between Unix and Datetime. I'll demonstrate how you can do that in Python.

Unix to Datetime

import time
from datetime import datetime
#convert unix to datetime
print(datetime.utcfromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
Enter fullscreen mode Exit fullscreen mode

Datetime to Unix

import time
from datetime import datetime
#convert unix to datetime
dtm = datetime.utcfromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')

#convert datetime back to unix
dtt = datetime.strptime(dtm, '%Y-%m-%d %H:%M:%S')
print(datetime.timestamp(dtt))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay