【发布时间】:2011-03-11 05:34:57
【问题描述】:
在 Python 中,如何找到计算机设置的 UTC 时间偏移量?
【问题讨论】:
在 Python 中,如何找到计算机设置的 UTC 时间偏移量?
【问题讨论】:
import time
print -time.timezone
它以秒为单位打印 UTC 偏移量(考虑夏令时 (DST),请参阅 time.altzone:
is_dst = time.daylight and time.localtime().tm_isdst > 0
utc_offset = - (time.altzone if is_dst else time.timezone)
其中 utc 偏移量通过以下方式定义:“要获取本地时间,请将 utc 偏移量添加到 utc 时间。”
在 Python 3.3+ 中有 tm_gmtoff attribute 如果底层 C 库支持它:
utc_offset = time.localtime().tm_gmtoff
注意:time.daylight 可能会在some edge cases 中给出错误的结果。
tm_gmtoff 如果在 Python 3.3+ 上可用,则由 datetime 自动使用:
from datetime import datetime, timedelta, timezone
d = datetime.now(timezone.utc).astimezone()
utc_offset = d.utcoffset() // timedelta(seconds=1)
要以一种解决time.daylight 问题的方法获取当前UTC 偏移量,并且即使tm_gmtoff 不可用也可以使用,@jts's suggestion 可用于子结构本地和UTC 时间:
import time
from datetime import datetime
ts = time.time()
utc_offset = (datetime.fromtimestamp(ts) -
datetime.utcfromtimestamp(ts)).total_seconds()
要获取过去/未来日期的 UTC 偏移量,可以使用 pytz 时区:
from datetime import datetime
from tzlocal import get_localzone # $ pip install tzlocal
tz = get_localzone() # local timezone
d = datetime.now(tz) # or some other local date
utc_offset = d.utcoffset().total_seconds()
它在 DST 转换期间有效,它适用于过去/未来的日期,即使当地时区在当时有不同的 UTC 偏移量,例如 2010-2015 年期间的欧洲/莫斯科时区。
【讨论】:
total_seconds() 仅在 Python 3.2+ 中可用。
total_seconds() 在 Python 2.7 和 it is easy to emulate it on earlier Python versions 中可用
gmtime() 将返回 UTC 时间,localtime() 将返回本地时间,因此减去两者应该会得到 UTC 偏移量。
来自https://pubs.opengroup.org/onlinepubs/009695399/functions/gmtime.html
gmtime() 函数应将自计时器指向的纪元以来的时间(以秒为单位)转换为细分时间,以协调世界时 (UTC) 表示。
因此,尽管名称为 gmttime,该函数仍返回 UTC。
【讨论】:
TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.struct_time'。你的真正意思是什么?
t = localtime(); timegm(t) - timegm(gmtime(mktime(t)))
gmtime() returns UTC always。有些情况下 GMT!=UTC 但不是这样。
我喜欢:
>>> strftime('%z')
'-0700'
我首先尝试了 JTS 的答案,但它给了我错误的结果。我现在在-0700,但有人说我在-0800。但是我必须进行一些转换才能得到可以减去的东西,所以答案可能比不正确更不完整。
【讨论】:
'%z' 不受 Python 支持(它可能适用于您可能可以使用 time.localtime().tm_gmtoff 代替的某些系统,以将 utc 偏移量作为数字而不是字符串获取)。结果('%z')应该与@jts 的答案相同。如果您不这么认为,请包含您的代码。
calendar.timegm() 或 datetime() 来查找差异
time module 有一个时区偏移量,以整数形式给出,单位为“UTC 以西的秒数”
import time
time.timezone
【讨论】:
您可以使用datetime 和dateutil 库将偏移量作为timedelta 对象:
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>>
>>> # From a datetime object
>>> current_time = datetime.now(tzlocal())
>>> current_time.utcoffset()
datetime.timedelta(seconds=7200)
>>> current_time.dst()
datetime.timedelta(seconds=3600)
>>>
>>> # From a tzlocal object
>>> time_zone = tzlocal()
>>> time_zone.utcoffset(datetime.now())
datetime.timedelta(seconds=7200)
>>> time_zone.dst(datetime.now())
datetime.timedelta(seconds=3600)
>>>
>>> print('Your UTC offset is {:+g}'.format(current_time.utcoffset().total_seconds()/3600))
Your UTC offset is +2
【讨论】:
hours_delta = (time.mktime(time.localtime()) - time.mktime(time.gmtime())) / 60 / 60
【讨论】:
这个简单的函数可以让您轻松地从 MySQL/PostgreSQL 数据库date 对象中获取当前时间。
def timestamp(date='2018-05-01'):
return int(time.mktime(
datetime.datetime.strptime( date, "%Y-%m-%d" ).timetuple()
)) + int(time.strftime('%z')) * 6 * 6
>>> timestamp('2018-05-01')
1525132800
>>> timestamp('2018-06-01')
1527811200
【讨论】:
这里是一些只有日期时间和时间作为导入的 python3 代码。高温
>>> from datetime import datetime
>>> import time
>>> def date2iso(thedate):
... strdate = thedate.strftime("%Y-%m-%dT%H:%M:%S")
... minute = (time.localtime().tm_gmtoff / 60) % 60
... hour = ((time.localtime().tm_gmtoff / 60) - minute) / 60
... utcoffset = "%.2d%.2d" %(hour, minute)
... if utcoffset[0] != '-':
... utcoffset = '+' + utcoffset
... return strdate + utcoffset
...
>>> date2iso(datetime.fromtimestamp(time.time()))
'2015-04-06T23:56:30-0400'
【讨论】:
这对我有用:
if time.daylight > 0:
return time.altzone
else:
return time.timezone
【讨论】:
time.daylight 没有说现在是不是夏天。它说当地时间可能有夏令时。这就是为什么你必须打电话给time.localtime().tm_isdst