比较两个isoformat日期时间字符串是否可靠? [英] Is it reliable to compare two isoformat datetime strings?

查看:63
本文介绍了比较两个isoformat日期时间字符串是否可靠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找出两个同格式的日期时间字符串中的哪个是最新的。



现在,我使用 datetime.strptime 方法。
然后我比较两个 datetime 对象。
然后我调用最大的 datetime 对象的 isoformat 以便将其作为get参数传递。 / p>

因此,我想知道在不进行从 str datetime



似乎可行:

 >>从datetime导入datetime开始为dt 
>> s1 =‘2013-12-25T19:20:41.391393’
>>> s2 =‘2013-12-25T19:20:41.391394’​​
>>> s1 s2

>>模式=‘%Y-%m-%dT%H:%M:%S.%f’
>> dt.strptime(s1,pattern)> dt.strptime(s2,pattern)
错误


解决方案

ISO 8601日期字符串(无时区偏移),它是 isoformat 可以作为字符串进行比较



作为 Assem-Hafez指出,如果字符串包含时区偏移量,则字符串比较可能不会产生与时区感知日期时间比较相同的结果:


[b]

 在[31]中:导入dateutil.parser为DP 

在[32]中:s = [ 2019-08-29T10 :50:35 + 00:00, 2019-08-29T10:50:35 + 02:00]

在[33]中:t = [si的DP.parse(si)在s]; t
Out [33]:
[datetime.datetime(2019,8,29,10,50,35,tzinfo = tzutc()),
datetime.datetime(2019,8, 29,10,50,35,tzinfo = tzoffset(None,7200))]

在[34]中:s [0]< s [1]
Out [34]:真

In [35]:t [0]< t [1]
Out [35]:错误


I need to find out which of two isoformatted datetime strings is the latest.

By now, I convert them using datetime.strptime method. Then I compare two datetime objects. Then I call isoformat of the greatest datetime object in order to pass it as a get parameter.

So I'm wondering if it is reliable to find out the greatest isoformatted string without doing converstion from str to datetime.

It seems to work:

>>> from datetime import datetime as dt
>>> s1 = '2013-12-25T19:20:41.391393'
>>> s2 = '2013-12-25T19:20:41.391394'
>>> s1 > s2
False
>>> pattern = '%Y-%m-%dT%H:%M:%S.%f'
>>> dt.strptime(s1, pattern) > dt.strptime(s2, pattern)
False

解决方案

ISO 8601 date strings (without timezone offset), which is the type of string returned by isoformat, can be compared as strings.

As Assem-Hafez points out, if the strings include timezone offsets, then string comparison may not produce the same result as timezone-aware datetime comparison:

In [31]: import dateutil.parser as DP

In [32]: s = ["2019-08-29T10:50:35+00:00", "2019-08-29T10:50:35+02:00"]

In [33]: t = [DP.parse(si) for si in s]; t
Out[33]: 
[datetime.datetime(2019, 8, 29, 10, 50, 35, tzinfo=tzutc()),
 datetime.datetime(2019, 8, 29, 10, 50, 35, tzinfo=tzoffset(None, 7200))]

In [34]: s[0] < s[1]
Out[34]: True

In [35]: t[0] < t[1]
Out[35]: False

这篇关于比较两个isoformat日期时间字符串是否可靠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆