如何将 Solr 日期转换回 python 可读日期,例如 'datetime'反之亦然?



是否有一种简单/有效的方法将'当前Solr日期'转换为'期望输出'如下所示?我想过使用正则表达式或字符串方法来清理Solr日期,但如果Python中有一种方法可以将这些日期从Solr转换过来,那就太好了。

目前Solr日期:

'2020-01-21T12:23:54.625Z'

期望输出值(datetime模块格式):


'2020-01-21 12:23:54' 

这里是一个从字符串到datetime对象再到字符串的快速往返,包括几个选项。希望这篇文章能让你振作起来。

string→datetime (微秒保存)

from datetime import datetime
s = '2020-01-21T12:23:54.625Z'
# to datetime object, including the Z (UTC):
dt_aware = datetime.fromisoformat(s.replace('Z', '+00:00'))
print(repr(dt_aware))
# datetime.datetime(2020, 1, 21, 12, 23, 54, 625000, tzinfo=datetime.timezone.utc)
# to datetime object, ignoring Z:
dt_naive = datetime.fromisoformat(s.strip('Z'))
print(repr(dt_naive))
# datetime.datetime(2020, 1, 21, 12, 23, 54, 625000)

datetime→string(微秒剥离)

# to isoformat string, space sep, no UTC offset, no microseconds
print(dt_aware.replace(microsecond=0, tzinfo=None).isoformat(' '))
# 2020-01-21 12:23:54
print(dt_naive.replace(microsecond=0).isoformat(' '))
# 2020-01-21 12:23:54
# ...or with a Z to specify UTC and a T as date/time separator
print(dt_aware.replace(microsecond=0).isoformat().replace('+00:00', 'Z'))
# 2020-01-21T12:23:54Z
# to isoformat string, with Z for UTC, naive / no tzinfo:
print(dt_naive.replace(microsecond=0).isoformat() + 'Z') # just add Z as a suffix
# 2020-01-21T12:23:54Z

您可能还想看一下datetime的时间标记变量。如果您需要特定的精度,例如毫秒。

相关内容

最新更新