gpt4 book ai didi

python - 带时区到纪元的日期时间

转载 作者:太空狗 更新时间:2023-10-29 20:33:04 24 4
gpt4 key购买 nike

在下面的代码中,我正在计算现在纪元和当天纪元的开始。

import time
import pytz
from datetime import datetime

tz1 = pytz.timezone('CST6CDT')
utc = pytz.timezone('UTC')
now = pytz.UTC.localize(datetime.utcnow())
now_tz = now.astimezone(tz1)
print now_tz
print now_tz.strftime('%s')

begin_day = now_tz.replace(hour=0, minute=0, second=0)
print begin_day

print begin_day.strftime('%s')

打印语句:

2012-08-28 13:52:21.595718-05:00
1346187141
2012-08-28 00:00:00.595718-05:00
1346137200

使用 CDT 时区将纪元转换为时间戳:1346187141 - 2012 年 8 月 28 日 15:52:21,1346137200 - 2012 年 8 月 28 日 02:00:00

我希望第二个纪元是一天的开始,但现在是凌晨 2 点。看起来它在转换为纪元时仍在使用本地时区 PST。

我做错了什么?还是可以用不同的方式完成?

谢谢!

最佳答案

将带时区的日期时间转换为纪元(POSIX 时间戳):

from datetime import datetime
import pytz

tz = pytz.timezone('CST6CDT')

# a datetime with timezone
dt_with_tz = tz.localize(datetime(2012, 8, 28, 19, 33, 50), is_dst=None)

# get timestamp
ts = (dt_with_tz - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
# -> 1346200430.0

这就是 datetime.timestamp 方法是如何在 Python 3 中为时区感知的 datetime 对象实现的。

获取“现在纪元”:

from datetime import datetime

now_epoch = (datetime.utcnow() - datetime(1970, 1, 1)).total_seconds()

或者(假设 time 使用 POSIX 纪元):

import time

now_epoch = time.time()

获取“当天纪元的开始”更加复杂,因为不同时区的当天可能不同:

from datetime import datetime, time
import pytz

tz = pytz.timezone('CST6CDT')

# get current date in given timezone
today = datetime.now(tz).date()
# -> datetime.date(2013, 6, 22)

# get beginning of current day in given timezone as a datetime with timezone
midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None)
# -> datetime.datetime(2013, 6, 22, 0, 0, tzinfo=<DstTzInfo 'CST6CDT'...>)

# get timestamp
ts = (midnight - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
# -> 1371877200.0

参见 How do I get the UTC time of “midnight” for a given timezone?

假设 UTC 日期获取“当前时间的开始”:

from datetime import datetime, date

# get current date in UTC
utc_date = datetime.utcnow().date()
# -> datetime.date(2013, 6, 23)

# get timestamp
ts = (utc_date - date(1970, 1, 1)).days * 86400
# -> 1371945600

参见 Converting datetime.date/datetime.datetime to UTC timestamp in Python

关于python - 带时区到纪元的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12165691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com