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.

Updated on: 2026-03-24T19:30:48+05:30

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements