Convert Python Timestamps to Datetime (and Back) – A Quick Guide
It's pretty common to store date and time as a timestamp in a database. A Unix timestamp is the number of seconds between a particular date and January 1, 1970 at UTC.
We can simply use the fromtimestamp() method from the datetime module to get a date from a UNIX timestamp.
Python timestamp to datetime
from datetime import datetime
# timestamp is number of seconds since 1970-01-01
timestamp = 1545730073
# convert the timestamp to a datetime object in the local timezone
dt_object = datetime.fromtimestamp(timestamp)
# print the datetime object and its type
print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))
Output
dt_object = 2018-12-25 09:27:53 type(dt_object) = <class 'datetime.datetime'>
Here, we have imported the datetime class from the datetime module.
Then, we used the datetime.fromtimestamp() class method which returns the local date and time (datetime object). This object is stored in the dt_object variable.
Note: We can easily create a string representing date and time from a datetime object using strftime() method.
Python datetime to timestamp
In Python, we can get timestamp from a datetime object using the datetime.timestamp() method. For example,
from datetime import datetime
# current date and time
now = datetime.now()
# convert from datetime to timestamp
ts = datetime.timestamp(now)
print("Timestamp =", ts)
Output
Timestamp = 1672138646.118119
Here, the datetime.timestamp() method takes a datetime object as an argument and returns a Unix timestamp.
Also Read:
- Python Program to Convert String to Datetime
Table of Contents
Python
- Python JSON: Encoding, Decoding, and File Handling – A Practical Guide
- Python OOP Fundamentals: Classes, Objects, Inheritance, and Constructors Explained
- Master Python Conditional Statements: IF, ELSE, ELIF, and Switch‑Like Logic
- Python Dictionaries: Adding, Updating, and Managing Key/Value Pairs
- Python vs Ruby: A Comprehensive Comparison of Features, Advantages, and Use Cases
- Python vs JavaScript: Key Differences, Features, and When to Choose Each
- Master Python File Handling: Create, Read, Write, and Open Text Files with Ease
- Build Python Skills Together: Cohort-Based Live Courses
- Python: Retrieve Current Time and Timezone Data with Ease
- Python List index() – How to Find Element Positions with Practical Examples