Python: 如何将 ISO 8601 格式的日期字符串与当前时间进行比较
Python: How to compare date string in ISO 8601 format with current time
date_str = '2022-03-29T17:49:35.914417-04:00'
如何将上面的日期字符串与当前日期时间进行比较?
尝试使用 datetime.<b>fromisoformat</b>(<i>date_string</i>)
to parse date_str
and then passing the determined timezone info into datetime.<b>now</b>(<i>tz=None</i>)
:
>>> from datetime import datetime
>>> date_str = '2022-03-29T17:49:35.914417-04:00'
>>> dt = datetime.fromisoformat(date_str)
>>> dt
datetime.datetime(2022, 3, 29, 17, 49, 35, 914417, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
>>> dt_now = datetime.now(dt.tzinfo)
>>> dt_now
datetime.datetime(2022, 5, 20, 15, 50, 58, 525908, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
>>> dt_now > dt
True
>>> dt_now - dt
datetime.timedelta(days=51, seconds=79282, microseconds=611491)
date_str = '2022-03-29T17:49:35.914417-04:00'
如何将上面的日期字符串与当前日期时间进行比较?
尝试使用 datetime.<b>fromisoformat</b>(<i>date_string</i>)
to parse date_str
and then passing the determined timezone info into datetime.<b>now</b>(<i>tz=None</i>)
:
>>> from datetime import datetime
>>> date_str = '2022-03-29T17:49:35.914417-04:00'
>>> dt = datetime.fromisoformat(date_str)
>>> dt
datetime.datetime(2022, 3, 29, 17, 49, 35, 914417, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
>>> dt_now = datetime.now(dt.tzinfo)
>>> dt_now
datetime.datetime(2022, 5, 20, 15, 50, 58, 525908, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
>>> dt_now > dt
True
>>> dt_now - dt
datetime.timedelta(days=51, seconds=79282, microseconds=611491)