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

Code_Jedi - May 30 '22 - - Dev Community

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
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .