DEV Community

Code_Jedi
Code_Jedi

Posted on

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)