Python 日期时间和 utc 偏移量转换忽略 timezone/daylight 节省
Python datetime and utc offset conversion ignoring timezone/daylight savings
我有两个操作要执行,一个与另一个相反。
我有一个 UTC 的 UNIX 时间戳,例如,1425508527。从这里我想得到年、月、日等给定的 UTC 偏移量。例如。 (UTC -6 小时)的 year/month/day/time 是什么?答案是 2015 年 3 月 4 日 16:35:27。在不提供偏移量(或偏移量零)的情况下,答案应该是 2015 年 3 月 4 日 22:35:27.
现在我有了某个位置的日期以及 UTC 偏移量。例如 2015 年 3 月 4 日 16:35:27 和偏移量(UTC -6 小时)。我应该得到的 UNIX UTC 时间戳应该是 1425508527。
我能够几乎 做 2。(使用 python 日期时间库)像这样:
import datetime.datetime as datetime
import time
import dateutil.tz as tz
utc_offset = 6
time.mktime(datetime(2015,3,4,16,35,27,
tzinfo=tz.tzoffset(None, utc_offset*60*60)).utctimetuple())
# => 1425486927
上面的问题是 utc_offset 必须给出错误的符号。根据this map,utc_offset应该设置为-6。第一。我没有运气。我不 need/want 处理夏令时等时区信息。我如何在 Python 中实现它?
如果您的系统使用 Unix time,
不计算闰秒,那么可以这样转换:
第 1 部分:时间戳和本地日期的偏移量
import datetime as DT
import calendar
timestamp = 1425508527
offset = -6
date = DT.datetime(1970,1,1) + DT.timedelta(seconds=timestamp)
print(date)
# 2015-03-04 22:35:27
localdate = date + DT.timedelta(hours=offset)
print(localdate)
# 2015-03-04 16:35:27
第 2 部分:本地日期和时间戳的偏移量
utcdate = localdate - DT.timedelta(hours=offset)
assert date == utcdate
timetuple = utcdate.utctimetuple()
timestamp2 = calendar.timegm(timetuple)
print(timestamp2)
# 1425508527
assert timestamp == timestamp2
我有两个操作要执行,一个与另一个相反。
我有一个 UTC 的 UNIX 时间戳,例如,1425508527。从这里我想得到年、月、日等给定的 UTC 偏移量。例如。 (UTC -6 小时)的 year/month/day/time 是什么?答案是 2015 年 3 月 4 日 16:35:27。在不提供偏移量(或偏移量零)的情况下,答案应该是 2015 年 3 月 4 日 22:35:27.
现在我有了某个位置的日期以及 UTC 偏移量。例如 2015 年 3 月 4 日 16:35:27 和偏移量(UTC -6 小时)。我应该得到的 UNIX UTC 时间戳应该是 1425508527。
我能够几乎 做 2。(使用 python 日期时间库)像这样:
import datetime.datetime as datetime
import time
import dateutil.tz as tz
utc_offset = 6
time.mktime(datetime(2015,3,4,16,35,27,
tzinfo=tz.tzoffset(None, utc_offset*60*60)).utctimetuple())
# => 1425486927
上面的问题是 utc_offset 必须给出错误的符号。根据this map,utc_offset应该设置为-6。第一。我没有运气。我不 need/want 处理夏令时等时区信息。我如何在 Python 中实现它?
如果您的系统使用 Unix time, 不计算闰秒,那么可以这样转换:
第 1 部分:时间戳和本地日期的偏移量
import datetime as DT
import calendar
timestamp = 1425508527
offset = -6
date = DT.datetime(1970,1,1) + DT.timedelta(seconds=timestamp)
print(date)
# 2015-03-04 22:35:27
localdate = date + DT.timedelta(hours=offset)
print(localdate)
# 2015-03-04 16:35:27
第 2 部分:本地日期和时间戳的偏移量
utcdate = localdate - DT.timedelta(hours=offset)
assert date == utcdate
timetuple = utcdate.utctimetuple()
timestamp2 = calendar.timegm(timetuple)
print(timestamp2)
# 1425508527
assert timestamp == timestamp2