How to Convert Unix time to datetime in Python

0
819
How to Convert Unix time to datetime in Python

Python does not have Date as a built-in data type, but we can import a module named datetime to work with date and time as objects. The datetime module supplies classes to work with date and time.

What is Unix time in Python?

Unix time in Python is the number of seconds that have elapsed since the Unix epoch, 00:00:00 UTC. The Unix epoch is  00:00:00 UTC on 1 January 1970. Unix time is also used to represent file timestamps (create and modify dates).

Converting the UNIX timestamp string to a readable date while handling dates in Python is required.

Python convert Unix time to datetime

To convert Unix time to datetime in Python, use the datetime.utcfromtimestamp().strftime() function. The strftime() is a built-in datetime module method that returns a string representing date and time using a date, time, or datetime object.

from datetime import datetime

unix = int("1664141445")
dttime = datetime.utcfromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S')
print(dttime)

Output

2022-09-25 21:30:45

To use the datetime module in Python, import the datetime module at the top of the file. Then, we defined a UNIX timestamp, and then to convert to the datetime, we used the datetime.utcfromtimestamp().strftime() function that will return the datetime.

Python convert Unix time to Date

To convert Unix time to date in Python, use the datetime.utcfromtimestamp().strftime(‘%Y-%m-%d) function. The strftime() function takes one or other format codes as an argument and returns a formatted string based on it.

from datetime import datetime

unix = int("1664141445")
date = datetime.utcfromtimestamp(unix).strftime('%Y-%m-%d')
print(date)

Output

2022-09-25

You can see that we only get the date in the output instead of the date and time.

Python convert datetime to Unix time

To convert datetime to Unix time in Python, use the timestamp() method. The timestamp() is a built-in datetime module method that returns the POSIX timestamp corresponding to the datetime instance. The return value of the timestamp() method is float.

from datetime import datetime

dttime = datetime.fromtimestamp(0)
print(dttime)
unix = dttime.timestamp()
print(unix)
print(type(unix))

Output

1970-01-01 05:30:00
0.0
<class 'float'>

You can see that we converted a datetime to a UNIX timestamp using the timestamp() method, and using the type() method, we can check that the return value is float.

That’s it for this tutorial.

Related posts

Python string to datetime

Python datetime to string

Python date format

Python time

Python time format

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.