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

Code_Jedi @code_jedi

About: Javascript, Node.js, Python, PHP, React and Vue. Coding since 2017

Joined:
Jul 8, 2021

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

Publish Date: May 30 '22
8 0

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

Comments 0 total

    Add comment