Python 如何获取包含默认时区的 isoformat 日期时间字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3401428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get an isoformat datetime string including the default timezone?
提问by deft_code
I need to produce a time string that matches the iso format yyyy-mm-ddThh:mm:ss.ssssss-ZO:NE. The now()and utcnow()class methods almost do what I want.
我需要生成一个与 iso 格式匹配的时间字符串yyyy-mm-ddThh:mm:ss.ssssss-ZO:NE。在now()和utcnow()类方法几乎做我想做的。
>>> import datetime
>>> #time adjusted for current timezone
>>> datetime.datetime.now().isoformat()
'2010-08-03T03:00:00.000000'
>>> #unadjusted UTC time
>>> datetime.datetime.utcnow().isoformat()
'2010-08-03T10:00:00.000000'
>>>
>>> #How can I do this?
>>> datetime.datetime.magic()
'2010-08-03T10:00:00.000000-07:00'
采纳答案by John Machin
Something like the following example. Note I'm in Eastern Australia (UTC + 10 hours at the moment).
类似于以下示例。请注意,我在澳大利亚东部(目前 UTC + 10 小时)。
>>> import datetime
>>> dtnow = datetime.datetime.now();dtutcnow = datetime.datetime.utcnow()
>>> dtnow
datetime.datetime(2010, 8, 4, 9, 33, 9, 890000)
>>> dtutcnow
datetime.datetime(2010, 8, 3, 23, 33, 9, 890000)
>>> delta = dtnow - dtutcnow
>>> delta
datetime.timedelta(0, 36000)
>>> hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60)
>>> hh,mm
(10, 0)
>>> "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
'2010-08-04T09:33:09.890000+10:00'
>>>
回答by Ofri Raviv
You need to make your datetime objects timezone aware. from the datetime docs:
您需要让您的日期时间对象了解时区。从日期时间文档:
There are two kinds of date and time objects: “naive” and “aware”. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment. Whether a naive datetime object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it's up to the program whether a particular number represents metres, miles, or mass. Naive datetime objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.
有两种日期和时间对象:“naive”和“aware”。这种区别是指对象是否有任何时区、夏令时或其他类型的算法或时间调整的概念。一个简单的 datetime 对象是否代表协调世界时 (UTC)、本地时间或其他时区的时间完全取决于程序,就像特定数字是否代表米、英里或质量取决于程序一样。朴素的日期时间对象易于理解和使用,但代价是忽略了现实的某些方面。
When you have an aware datetime object, you can use isoformat() and get the output you need.
当您有一个知道日期时间对象时,您可以使用 isoformat() 并获得您需要的输出。
To make your datetime objects aware, you'll need to subclass tzinfo, like the second example in here, or simpler - use a package that does it for you, like pytzor python-dateutil
为了让你的日期时间对象知道,你需要子类化 tzinfo,就像这里的第二个例子,或者更简单 - 使用一个为你做的包,比如pytz或python-dateutil
Using pytz, this would look like:
使用 pytz,这看起来像:
import datetime, pytz
datetime.datetime.now(pytz.timezone('US/Central')).isoformat()
You can also control the output format, if you use strftime with the '%z' format directivelike
您还可以控制输出格式,如果您将 strftime 与'%z' 格式指令一起使用,例如
datetime.datetime.now(pytz.timezone('US/Central')).strftime('%Y-%m-%dT%H:%M:%S.%f%z')
回答by jfs
To get the current time in UTC in Python 3.2+:
要在 Python 3.2+ 中以 UTC 格式获取当前时间:
>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2015-01-27T05:57:31.399861+00:00'
To get local time in Python 3.3+:
要在 Python 3.3+ 中获取本地时间:
>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).astimezone().isoformat()
'2015-01-27T06:59:17.125448+01:00'
Explanation: datetime.now(timezone.utc)produces a timezone aware datetimeobject in UTC time. astimezone()then changes the timezone of the datetimeobject, to the system's locale timezone if called with no arguments. Timezone aware datetimeobjects then produce the correct ISO format automatically.
说明:以 UTC 时间datetime.now(timezone.utc)生成时区感知datetime对象。astimezone()然后将datetime对象的时区更改为系统的语言环境时区(如果不带参数调用)。时区感知datetime对象然后自动生成正确的 ISO 格式。
回答by Wes Turner
回答by Dmitry Shesterkin
You can do it in Python 2.7+ with python-dateutil(which is insalled on Mac by default):
您可以在 Python 2.7+ 中使用python-dateutil(默认情况下在 Mac 上安装):
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> datetime.now(tzlocal()).isoformat()
'2016-10-22T12:45:45.353489-03:00'
Or you if you want to convert from an existed stored string:
或者,如果您想从现有的存储字符串转换:
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> from dateutil.parser import parse
>>> parse("2016-10-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-10-21T16:33:27.696173-03:00' <-- Atlantic Daylight Time (ADT)
>>> parse("2016-01-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-01-21T16:33:27.696173-04:00' <-- Atlantic Standard Time (AST)

