Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to convert an integer into a date object in Python?
You can convert an integer representing a UNIX timestamp into a date object using Python's datetime module. The fromtimestamp() function takes the timestamp as input and returns the corresponding datetime object.
Basic Conversion Using fromtimestamp()
The simplest approach is to use datetime.fromtimestamp() ?
import datetime
timestamp = 1500000000
date_obj = datetime.datetime.fromtimestamp(timestamp)
print(date_obj.strftime('%Y-%m-%d %H:%M:%S'))
2017-07-14 08:10:00
Converting to Date Only
If you only need the date part without time, use the date() method ?
import datetime timestamp = 1500000000 date_obj = datetime.datetime.fromtimestamp(timestamp) date_only = date_obj.date() print(date_only) print(type(date_only))
2017-07-14 <class 'datetime.date'>
Using UTC Timezone
For UTC timestamps, use utcfromtimestamp() to avoid timezone confusion ?
import datetime
timestamp = 1500000000
utc_date = datetime.datetime.utcfromtimestamp(timestamp)
print("UTC:", utc_date.strftime('%Y-%m-%d %H:%M:%S'))
local_date = datetime.datetime.fromtimestamp(timestamp)
print("Local:", local_date.strftime('%Y-%m-%d %H:%M:%S'))
UTC: 2017-07-14 02:40:00 Local: 2017-07-14 08:10:00
Handling Different Timestamp Formats
Sometimes timestamps are in milliseconds instead of seconds ?
import datetime
# Timestamp in milliseconds
timestamp_ms = 1500000000000
timestamp_seconds = timestamp_ms / 1000
date_obj = datetime.datetime.fromtimestamp(timestamp_seconds)
print(date_obj.strftime('%Y-%m-%d %H:%M:%S'))
2017-07-14 08:10:00
Conclusion
Use datetime.fromtimestamp() to convert integer timestamps to datetime objects. For date-only objects, call .date() on the result. Use utcfromtimestamp() for UTC timestamps to avoid timezone issues.
Advertisements
