Python:将Epoch时间戳转换为指定格式日期字符串(支持CAT时区)
Got it, let's work through converting those Unix epoch timestamps to dd/mm/yyyy dates, with priority given to the CAT (UTC+2) timezone. This is a common task in web scraping, so here are practical solutions in two widely used languages for this work:
Python Solution
Python's datetime module makes this straightforward. Since your timestamps are second-based (not millisecond), we'll convert them directly to timezone-aware datetime objects, then format them to the desired string.
from datetime import datetime, timedelta, timezone # Define the CAT timezone (UTC+2) cat_tz = timezone(timedelta(hours=2)) # Example timestamps from your question sample_timestamps = [1508486400, 1510974000, 1388664000] for ts in sample_timestamps: # Convert timestamp to a CAT datetime object cat_datetime = datetime.fromtimestamp(ts, tz=cat_tz) # Format to dd/mm/yyyy formatted_date = cat_datetime.strftime("%d/%m/%Y") print(f"Timestamp {ts} → {formatted_date}")
Output:
Timestamp 1508486400 → 20/10/2017 Timestamp 1510974000 → 18/11/2017 Timestamp 1388664000 → 02/01/2014
This matches the sample dates you provided (when adjusted to CAT). If you ever need to use a different timezone, just modify the timedelta(hours=X) value.
JavaScript Solution
For Node.js or browser-based scraping, use the Intl.DateTimeFormat API to handle timezone formatting cleanly. Note that JavaScript's Date object expects millisecond-based timestamps, so we'll multiply your input values by 1000 first.
// Sample second-based timestamps const timestamps = [1508486400, 1510974000, 1388664000]; // Set up formatter for CAT (using a valid CAT timezone identifier) const dateFormatter = new Intl.DateTimeFormat('en-GB', { timeZone: 'Africa/Johannesburg', // UTC+2, part of CAT day: '2-digit', month: '2-digit', year: 'numeric' }); timestamps.forEach(ts => { // Convert seconds to milliseconds const date = new Date(ts * 1000); const formattedDate = dateFormatter.format(date); console.log(`Timestamp ${ts} → ${formattedDate}`); });
Output:
Timestamp 1508486400 → 20/10/2017 Timestamp 1510974000 → 18/11/2017 Timestamp 1388664000 → 02/01/2014
We use en-GB locale here because it defaults to the dd/mm/yyyy format. You can swap in other CAT timezone identifiers like Africa/Harare or Africa/Lusaka if needed—they all map to UTC+2.
Quick Notes:
- Always confirm if your timestamps are second or millisecond based (yours are seconds, so adjust accordingly).
- If timezone isn't mandatory, you can omit the
timeZoneparameter to use the system's local timezone, or set it toUTCfor universal time.
内容的提问来源于stack exchange,提问作者toyo10

