Working with timestamps is common when scraping or processing API data. Unix timestamps, although precise, are not human-readable, so formatting them into standard date-time strings is necessary.
Core Conversion Approaches
Python provides a few straightforward ways to transform a numeric timestamp. Below are two practical methods using the standard library.
Using time module
First, import the module and convert the raw integer or float to a structured time object using localtime(). Then apply strftime() to define the output pattern.
import time
raw_ts = 1698393600
time_struct = time.localtime(raw_ts)
formatted = time.strftime("%Y/%m/%d %H:%M:%S", time_struct)
print(formatted) # Example: 2023/10/27 08:00:00
Using datetime module
You can also rely on datetime.datetime.fromtimestamp() which returns a datetime object directly. Call strftime() on it to get the string representation.
from datetime import datetime
raw_ts = 1698393600
dt_object = datetime.fromtimestamp(raw_ts)
readable_date = dt_object.strftime("%Y-%m-%d %H:%M:%S")
print(readable_date) # Example: 2023-10-27 08:00:00
For UTC-based conversions, utcfromtimestamp() is available, though datetime.datetime.fromtimestamp(timestamp, tz=timezone.utc) is recommended in Python 3.
Applying Conversion in a Scraping Context
Assume you have extrcated a story tuple where story_item[2] holds a timestamp string. You want to replace the raw number with a formatted date in your output.
Original snippet producing raw timestamp
print("Page %d\tAuthor: %s\tTime: %s\tLikes: %s\n%s" % (
current_page, story_item[0], story_item[2], story_item[3], story_item[1]
))
Revised snippet with conversion
import time
for story_item in stories:
ts_as_float = float(story_item[2])
structured_time = time.localtime(ts_as_float)
nice_time = time.strftime("%Y-%m-%d %H:%M:%S", structured_time)
print("Page %d\tAuthor: %s\tTime: %s\tLikes: %s\n%s" % (
current_page, story_item[0], nice_time, story_item[3], story_item[1]
))
An alternative one-liner using the datetime module:
from datetime import datetime
print("Page %d\tAuthor: %s\tTime: %s\tLikes: %s\n%s" % (
current_page,
story_item[0],
datetime.fromtimestamp(float(story_item[2])).strftime("%Y-%m-%d %H:%M:%S"),
story_item[3],
story_item[1]
))
Both techniques will turn an integer like 1445500414 into a readable string such as 2015-10-22 15:53:34. Choose the one that fits your time zone needs and coding style.