veighna-global / vnpy_binance

Binance trading gateway for VeighNa Evo
MIT License
236 stars 100 forks source link

修复时区设置错误 #48

Closed lanceyliao closed 5 months ago

lanceyliao commented 5 months ago

运行以下代码可见错误之处。

from datetime import datetime, timezone, timedelta

# 定义 UTC 时区
UTC_TZ = ZoneInfo("UTC")

# 定义一个本地时区,假设为 UTC+8
LOCAL_TZ = timezone(timedelta(hours=8))

# 生成 timestamp,以 2021-07-01 08:30:00 UTC 为例
dt_raw = datetime(2021, 7, 1, 8, 30, tzinfo=UTC_TZ)
timestamp = dt_raw.timestamp() * 1000

def generate_datetime_with_tz(timestamp: float) -> datetime:
    """Generate datetime object from timestamp using tz parameter"""
    dt = datetime.fromtimestamp(timestamp / 1000, tz=UTC_TZ)
    return dt

def generate_datetime_with_replace(timestamp: float) -> datetime:
    """Generate datetime object from timestamp and then replace tzinfo"""
    dt = datetime.fromtimestamp(timestamp / 1000)
    dt = dt.replace(tzinfo=UTC_TZ)
    return dt

# 测试生成的 datetime 对象
dt_with_tz = generate_datetime_with_tz(timestamp)
dt_with_replace = generate_datetime_with_replace(timestamp)

# 输出结果
print("Using tz parameter:")
print(f"dt_with_tz: {dt_with_tz}")
print(f"dt_with_tz time zone: {dt_with_tz.tzinfo}")
print("="*40)
print("Using replace method:")
print(f"dt_with_replace: {dt_with_replace}")
print(f"dt_with_replace time zone: {dt_with_replace.tzinfo}")

# 对比本地时区生成的 datetime
dt_with_local = datetime.fromtimestamp(timestamp / 1000, tz=LOCAL_TZ)
print("="*40)
print("Using local time zone:")
print(f"dt_with_local: {dt_with_local}")
print(f"dt_with_local time zone: {dt_with_local.tzinfo}")

结果:

Using tz parameter: dt_with_tz: 2021-07-01 08:30:00+00:00 dt_with_tz time zone: UTC

Using replace method: dt_with_replace: 2021-07-01 16:30:00+00:00 dt_with_replace time zone: UTC

Using local time zone: dt_with_local: 2021-07-01 16:30:00+08:00 dt_with_local time zone: UTC+08:00

veighna-global commented 5 months ago

PR merged. Thanks a lot for your contribution!