You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 timeZone parameter to use the system's local timezone, or set it to UTC for universal time.

内容的提问来源于stack exchange,提问作者toyo10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:53:01