如何将本地时间字符串转换为 UTC?
如何将日期时间本地时间字符串转换为UTC时间字符串?
我确信我以前做过这个,但找不到它,所以希望将来能帮助我(和其他人)做到这一点。
说明:例如,如果我的本地时区 (+10
) 为 2008-09-17 14:02:00
,我'我想生成一个具有等效 UTC
时间的字符串:2008-09-17 04:02:00
。
另外,来自 http://lucumr.pocoo.org/2011/7 /15/eppur-si-muove/,请注意,一般来说这是不可能的,因为 DST 和其他问题没有从本地时间到 UTC 时间的唯一转换。
How do I convert a datetime string in local time to a string in UTC time?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
Clarification: For example, if I have 2008-09-17 14:02:00
in my local timezone (+10
), I'd like to generate a string with the equivalent UTC
time: 2008-09-17 04:02:00
.
Also, from http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(26)
默认的
datetime
对象不会设置时区(tzinfo
属性将为None
),因此在将字符串解析为 datetime 对象后,时区应转换为 UTC:The default
datetime
object will have no timezone set up (tzinfo
property will beNone
), so after parsing the string into the datetime object, the timezone should be convert to UTC:如果您已经有一个日期时间对象
my_dt
,您可以将其更改为 UTC:If you already have a datetime object
my_dt
you can change it to UTC with:简单地说,将任何
datetime
日期转换为UTC时间:让我们用一个例子来解释。 首先,我们需要从字符串创建一个
datetime
:然后,我们可以调用该函数:
逐步了解该函数的工作原理:
Briefly, to convert any
datetime
date to UTC time:Let's explain with an example. First, we need to create a
datetime
from the string:Then, we can call the function:
Step by step how the function works:
在 python3 中:
pip install python-dateutil
In python3:
pip install python-dateutil
怎么样 -
如果秒是
None
那么它将本地时间转换为 UTC 时间,否则将传递的时间转换为 UTC。How about -
if seconds is
None
then it converts the local time to UTC time else converts the passed in time to UTC.首先,将字符串解析为一个简单的日期时间对象。 这是一个没有附加时区信息的
datetime.datetime
实例。 请参阅其文档。使用
pytz
模块,该模块附带完整的时区列表 + UTC。 找出本地时区是什么,从中构造一个时区对象,然后操作它并将其附加到原始日期时间。最后,使用 datetime.astimezone() 方法将日期时间转换为 UTC。
源代码,使用本地时区“America/Los_Angeles”,对于字符串“2001-2-3 10:11:12”:
从那里,您可以使用
strftime()
方法来格式化 UTC根据需要的日期时间:First, parse the string into a naive datetime object. This is an instance of
datetime.datetime
with no attached timezone information. See its documentation.Use the
pytz
module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.Finally, use
datetime.astimezone()
method to convert the datetime to UTC.Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":
From there, you can use the
strftime()
method to format the UTC datetime as needed:注意 - 从 2020 年起,您不应使用
.utcnow()
或.utcfromtimestamp(xxx)
。 由于您可能已经转向 python3,因此您应该使用时区感知的日期时间对象。详情请参阅:https://blog.ganssle.io/articles/2019/11 /utcnow.html
原始答案(从 2010 年开始):
datetime 模块的 utcnow()函数可用于获取当前UTC时间。
正如汤姆上面提到的链接:http://lucumr.pocoo。 org/2011/7/15/eppur-si-muove/ 说:
注意 - 如果您的任何数据位于使用 DST 的地区,请使用
pytz
并看看 John Millikin 的回答。如果您想从给定字符串获取 UTC 时间,并且您很幸运地位于世界上不使用 DST 的地区,或者您拥有的数据仅与 UTC 存在偏移而未应用 DST:
-- > 使用当地时间作为偏移值的基础:
--> 或者,从已知的偏移量开始,使用 datetime.timedelta():
更新:
由于 python 3.2
datetime.timezone
可用。 您可以使用以下命令生成时区感知日期时间对象:如果您准备好进行时区转换,请阅读以下内容:
https://medium.com/@eleroy/10-things-you-需要了解 python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7 中的日期和时间
NOTE -- As of 2020 you should not be using
.utcnow()
or.utcfromtimestamp(xxx)
. As you've presumably moved on to python3,you should be using timezone aware datetime objects.For details see: https://blog.ganssle.io/articles/2019/11/utcnow.html
original answer (from 2010):
The datetime module's utcnow() function can be used to obtain the current UTC time.
As the link mentioned above by Tom: http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/ says:
NOTE - If any of your data is in a region that uses DST, use
pytz
and take a look at John Millikin's answer.If you want to obtain the UTC time from a given string and you're lucky enough to be in a region in the world that either doesn't use DST, or you have data that is only offset from UTC without DST applied:
--> using local time as the basis for the offset value:
--> Or, from a known offset, using datetime.timedelta():
UPDATE:
Since python 3.2
datetime.timezone
is available. You can generate a timezone aware datetime object with the command below:If your ready to take on timezone conversions go read this:
https://medium.com/@eleroy/10-things-you-need-to-know-about-date-and-time-in-python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7
谢谢@rofly,从字符串到字符串的完整转换如下:
我对
time
/calendar
函数的总结:time.strptime
字符串 --> 元组(未应用时区,因此匹配字符串)
time.mktime
本地时间元组 --> 自纪元以来的秒数(始终为当地时间)
time.gmtime
自纪元以来的秒数 --> UTC
和
calendar.timegm
中的元组
UTC 元组 --> 自纪元以来的秒数
time.localtime
自纪元以来的秒数 --> 本地时区的元组
Thanks @rofly, the full conversion from string to string is as follows:
My summary of the
time
/calendar
functions:time.strptime
string --> tuple (no timezone applied, so matches string)
time.mktime
local time tuple --> seconds since epoch (always local time)
time.gmtime
seconds since epoch --> tuple in UTC
and
calendar.timegm
tuple in UTC --> seconds since epoch
time.localtime
seconds since epoch --> tuple in local timezone
对于任何对最高票数答案感到困惑的人。 您可以通过生成日期时间对象将日期时间字符串转换为 python 中的 utc 时间,然后可以使用 astimezone(pytz.utc) 获取 utc 中的日期时间。
例如。
假设我们有 isoformat 格式的本地日期时间字符串
2021-09-02T19:02:00Z
现在将此字符串转换为 utc 日期时间。 使用此字符串生成 datetime 对象,
我们首先需要通过dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')
这将为您提供 python datetime 对象,那么您可以使用
astimezone(pytz.utc)
获取 utc 日期时间,例如dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M :%SZ') dt = dt.astimezone(pytz.utc)
这将为您提供 utc 格式的日期时间对象,然后您可以使用 dt.strftime("%Y-%m- %d %H:%M:%S")
完整代码,例如:
然后您可以将其称为
converLocalToUTC("2021-09-02T19:02:00Z")
获得帮助
https://stackoverflow.com/a/79877/7756843
For anyone who is confused with the most upvoted answer. You can convert a datetime string to utc time in python by generating a datetime object and then you can use astimezone(pytz.utc) to get datetime in utc.
For eg.
let say we have local datetime string as
2021-09-02T19:02:00Z
in isoformatNow to convert this string to utc datetime. we first need to generate datetime object using this string by
dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')
this will give you python datetime object, then you can use
astimezone(pytz.utc)
to get utc datetime likedt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ') dt = dt.astimezone(pytz.utc)
this will give you datetime object in utc, then you can convert it to string using
dt.strftime("%Y-%m-%d %H:%M:%S")
full code eg:
then you can call it as
converLocalToUTC("2021-09-02T19:02:00Z")
took help from
https://stackoverflow.com/a/79877/7756843
我在此处找到了另一个问题的最佳答案。 它只使用 python 内置库,不需要您输入本地时区(在我的情况下是一个要求)
我在这里重新发布答案,因为这个问题会在谷歌中弹出,而不是根据搜索关键字弹出的链接问题。
I found the best answer on another question here. It only uses python built-in libraries and does not require you to input your local timezone (a requirement in my case)
I'm reposting the answer here since this question pops up in google instead of the linked question depending on the search keywords.
我的一个项目中有这样的代码:
I have this code in one of my projects:
使用 http://crsmithdev.com/arrow/
这个库让生活变得轻松:)
Using http://crsmithdev.com/arrow/
This library makes life easy :)
为了避开夏令时等。
上述答案都没有对我有特别帮助。 下面的代码适用于 GMT。
For getting around day-light saving, etc.
None of the above answers particularly helped me. The code below works for GMT.
在 python 3.9.0 中,将本地时间
local_time
解析为datetime.datetime
对象后,只需使用local_time.astimezone(datetime.timezone.utc)
。In python 3.9.0, after you've parsed your local time
local_time
intodatetime.datetime
object, just uselocal_time.astimezone(datetime.timezone.utc)
.你可以这样做:
You can do it with:
怎么样 -
如果秒是
None
那么它将本地时间转换为 UTC 时间,否则将传递的时间转换为 UTC。How about -
if seconds is
None
then it converts the local time to UTC time else converts the passed in time to UTC.很简单
,我是这样实现的:
奇特的实现
如果你想变得奇特,你可以把它变成一个函子:
结果:
Simple
I did it like this:
Fancy Implementation
If you want to get fancy, you can turn this into a functor:
Result:
如果您更喜欢 datetime.datetime:
if you prefer datetime.datetime:
下面是 Python3.9zoneinfo 模块的示例strong>:
在您要转换的时区不反映系统本地时区的情况下,这可能比仅使用 dt.astimezone() 更好。 不必依赖外部库也很好。
注意:这可能不适用于 Windows 系统,因为 zoneinfo 依赖于可能不存在的 IANA 数据库。 可以安装 tzdata 包作为解决方法。 它是第一方包,但不在标准库中。
Here's an example with the native zoneinfo module in Python3.9:
This may be preferred over just using
dt.astimezone()
in situations where the timezone you're converting from isn't reflective of your system's local timezone. Not having to rely on external libraries is nice too.Note: This may not work on Windows systems, since zoneinfo relies on an IANA database that may not be present. The tzdata package can be installed as a workaround. It's a first-party package, but is not in the standard library.
我在 python-dateutil 方面取得了最大的成功:
I've had the most success with python-dateutil:
还有一个使用 pytz 的示例,但包含 localize(),这拯救了我的一天。
One more example with pytz, but includes localize(), which saved my day.
来源:http://feihonghsu.blogspot。 com/2008/02/converting-from-local-time-to-utc.html
来自 bd808:如果您的源是
datetime.datetime
对象t
,则调用为:Source: http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html
Example usage from bd808: If your source is a
datetime.datetime
objectt
, call as:我对 dateutil 很幸运(对于其他相关问题,它被广泛推荐):(
代码源自此答案 Convert UTC datetime string to local datetime)
I'm having good luck with dateutil (which is widely recommended on SO for other related questions):
(Code was derived from this answer to Convert UTC datetime string to local datetime)
以下是常见 Python 时间转换的摘要。
有些方法会丢失几分之一秒,并用 (s) 标记。 可以使用诸如
ts = (d - epoch)/unit
之类的显式公式来代替(感谢 jfs)。calendar.timegm(struct_time)
calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())
(DST 转换期间的异常,请参阅 jfs 的评论)
calendar.timegm(dt.utctimetuple())
calendar.timegm(dt.utctimetuple())
time.gmtime(t)
< br>(参见 jfs 的评论)stz.localize(dt, is_dst=None).utctimetuple()
(DST 转换期间的异常,请参阅 jfs 的评论)
dt.utctimetuple()
dt.utctimetuple()
datetime.fromtimestamp (t,无)
(在某些情况下可能会失败,请参阅下面 jfs 的评论)
datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
(无法表示闰秒,请参阅 jfs 的评论)
dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
dt.astimezone(tz).replace(tzinfo=None)
datetime.utcfromtimestamp(t)
datetime.datetime(*struct_time[:6])
(不能表示闰秒,请参阅评论jfs)
stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)
( DST 转换期间出现异常,请参阅 jfs 的评论)
dt.astimezone(UTC).replace(tzinfo=None)
datetime.fromtimestamp(t, tz)
(对于非 pytz 时区可能会失败)
datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)
(不能表示闰秒,请参阅 jfs 的评论)
stz.localize(dt, is_dst=None)
(DST 转换期间的异常,请参阅 jfs 的评论)
dt。替换(tzinfo=UTC)
来源:taaviburns.ca
Here's a summary of common Python time conversions.
Some methods drop fractions of seconds, and are marked with (s). An explicit formula such as
ts = (d - epoch) / unit
can be used instead (thanks jfs).calendar.timegm(struct_time)
calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())
(exception during DST transitions, see comment from jfs)
calendar.timegm(dt.utctimetuple())
calendar.timegm(dt.utctimetuple())
time.gmtime(t)
(see comment from jfs)
stz.localize(dt, is_dst=None).utctimetuple()
(exception during DST transitions, see comment from jfs)
dt.utctimetuple()
dt.utctimetuple()
datetime.fromtimestamp(t, None)
(may fail in certain conditions, see comment from jfs below)
datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
(can't represent leap seconds, see comment from jfs)
dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
dt.astimezone(tz).replace(tzinfo=None)
datetime.utcfromtimestamp(t)
datetime.datetime(*struct_time[:6])
(can't represent leap seconds, see comment from jfs)
stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)
(exception during DST transitions, see comment from jfs)
dt.astimezone(UTC).replace(tzinfo=None)
datetime.fromtimestamp(t, tz)
(may fail for non-pytz timezones)
datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)
(can't represent leap seconds, see comment from jfs)
stz.localize(dt, is_dst=None)
(exception during DST transitions, see comment from jfs)
dt.replace(tzinfo=UTC)
Source: taaviburns.ca
自 Python 3.6 起可用的选项:
datetime.astimezone(tz=None)
可用于获取表示本地时间的感知日期时间对象(文档)。 然后可以轻松地将其转换为 UTC。.astimezone()
将 datetime 对象的tzinfo
设置为 timedelta 派生的时区 - 所以不要期望任何“ DST 意识”来自它。 这里要小心 timedelta 算术。 当然,除非您先转换为 UTC。An option available since Python 3.6:
datetime.astimezone(tz=None)
can be used to get an aware datetime object representing local time (docs). This can then easily be converted to UTC..astimezone()
setstzinfo
of the datetime object to a timedelta-derived timezone - so don't expect any "DST-awareness" from it. Be careful with timedelta arithmetic here. Unless you convert to UTC first of course.