[转载]|[转载] 如何将ISO 8601日期时间字符串转换为Python日期时间对象( [重复])
参考链接: Python | 输出格式化 output format
本文翻译自:How do I translate an ISO 8601 datetime string into a Python datetime object? [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
How do I parse an ISO 8601-formatted date? 如何解析ISO 8601格式的日期? 26 answers 26个答案
I'm getting a datetime string in a format like "2009-05-28T16:15:00" (this is ISO 8601, I believe). 我正在以类似“ 2009-05-28T16:15:00”的格式获取日期时间字符串(我相信这是ISO 8601)。 One hackish option seems to be to parse the string using time.strptime and passing the first six elements of the tuple into the datetime constructor, like: 一种可能的选择似乎是使用time.strptime解析字符串,并将元组的前六个元素传递到datetime构造函数中,例如:
datetime.datetime(*time.strptime("2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")[:6])
I haven't been able to find a "cleaner" way of doing this. 我还没有找到一种“清洁”的方法。 Is there one? 有一个吗?
#1楼
参考:https://stackoom.com/question/449d/如何将ISO-日期时间字符串转换为Python日期时间对象-重复
#2楼
import datetime, time
def convert_enddate_to_seconds(self, ts):
"""Takes ISO 8601 format(string) and converts into epoch time."""
dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\
datetime.timedelta(hours=int(ts[-5:-3]),
minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
return seconds
This also includes the milliseconds and time zone. 这还包括毫秒和时区。
If the time is '2012-09-30T15:31:50.262-08:00', this will convert into epoch time. 如果时间是“ 2012-09-30T15:31:50.262-08:00”,则它将转换为纪元时间。
>>> import datetime, time
>>> ts = '2012-09-30T15:31:50.262-08:00'
>>> dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
>>> seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
>>> seconds
1348990310.26
#3楼
Arrow looks promising for this: Arrow对此很有希望:
>>> import arrow
>>> arrow.get('2014-11-13T14:53:18.694072+00:00').datetime
datetime.datetime(2014, 11, 13, 14, 53, 18, 694072, tzinfo=tzoffset(None, 0))
【[转载]|[转载] 如何将ISO 8601日期时间字符串转换为Python日期时间对象( [重复])】Arrow is a Python library that provides a sensible, intelligent way of creating, manipulating, formatting and converting dates and times. Arrow是一个Python库,它提供了一种明智,智能的方式来创建,操作,格式化和转换日期和时间。 Arrow is simple, lightweight and heavily inspired by moment.js and requests . Arrow很简单,轻巧,并且受moment.js和request的启发很大 。
#4楼
You should keep an eye on the timezone information, as you might get into trouble when comparing non-tz-aware datetimes with tz-aware ones. 您应该注意时区信息,因为在比较非tz感知的日期时间和tz感知的日期时间时可能会遇到麻烦。
It's probably the best to always make them tz-aware (even if only as UTC), unless you really know why it wouldn't be of any use to do so. 最好始终使它们具有tz意识(即使仅作为UTC),除非您真的知道为什么这样做没有任何用处。
#-----------------------------------------------
import datetime
import pytz
import dateutil.parser
#-----------------------------------------------
utc = pytz.utc
BERLIN = pytz.timezone('Europe/Berlin')
#-----------------------------------------------
def to_iso8601(when=None, tz=BERLIN):
if not when:
when = datetime.datetime.now(tz)
if not when.tzinfo:
when = tz.localize(when)
_when = when.strftime("%Y-%m-%dT%H:%M:%S.%f%z")
return _when[:-8] + _when[-5:] # Remove microseconds
#-----------------------------------------------
def from_iso8601(when=None, tz=BERLIN):
_when = dateutil.parser.parse(when)
if not _when.tzinfo:
_when = tz.localize(_when)
return _when
#-----------------------------------------------
#5楼
aniso8601 should handle this. aniso8601应该处理这个问题。 It also understands timezones, Python 2 and Python 3, and it has a reasonable coverage of the rest of ISO 8601 , should you ever need it. 它还了解时区,Python 2和Python 3,并且在需要时可以合理涵盖ISO 8601的其余部分。
import aniso8601
aniso8601.parse_datetime('2007-03-04T21:08:12')
#6楼
Because ISO 8601 allows many variations of optional colons and dashes being present, basically CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm] . 由于ISO 8601允许存在许多可选的冒号和破折号,因此基本上CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm] 。 If you want to use strptime, you need to strip out those variations first. 如果要使用strptime,则需要先删除这些变化。
The goal is to generate a UTC datetime object. 目标是生成UTC日期时间对象。
If you just want a basic case that work for UTC with the Z suffix like 2016-06-29T19:36:29.3453Z : 如果您只想使用带有Z后缀的UTC的基本情况,例如2016-06-29T19:36:29.3453Z :
datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")
If you want to handle timezone offsets like 2016-06-29T19:36:29.3453-0400 or 2008-09-03T20:56:35.450686+05:00 use the following. 如果要处理时区偏移,例如2016-06-29T19:36:29.3453-0400或2008-09-03T20:56:35.450686+05:00使用以下内容。 These will convert all variations into something without variable delimiters like 20080903T205635.450686+0500 making it more consistent/easier to parse. 这些会将所有变体转换成没有变量定界符的内容,例如20080903T205635.450686+0500 ,使其更一致/更容易解析。
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )
If your system does not support the %z strptime directive (you see something like ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z' ) then you need to manually offset the time from Z (UTC). 如果您的系统不支持%z strptime指令(您会看到类似ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z' ),则需要手动从Z (UTC)偏移时间。 Note %z may not work on your system in Python versions < 3 as it depended on the C library support which varies across system/Python build type (ie, Jython , Cython , etc.). 注意%z可能在版本低于3的Python版本中无法在您的系统上运行,因为它取决于C库支持,该支持因系统/ Python构建类型(即Jython , Cython等)而异。
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split(r"[+|-]",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
推荐阅读
- 考研英语阅读终极解决方案——阅读理解如何巧拿高分
- 如何寻找情感问答App的分析切入点
- 即将到手三百万
- mybatisplus如何在xml的连表查询中使用queryWrapper
- MybatisPlus使用queryWrapper如何实现复杂查询
- 思友人
- 如何在Mac中的文件选择框中打开系统隐藏文件夹
- 漫画初学者如何学习漫画背景的透视画法(这篇教程请收藏好了!)
- java中如何实现重建二叉树
- Linux下面如何查看tomcat已经使用多少线程