如何将Solr日期转换回python可读的日期,例如&x27;日期时间';反之亦然?

如何将Solr日期转换回python可读的日期,例如&x27;日期时间';反之亦然?,python,datetime,solr,pysolr,Python,Datetime,Solr,Pysolr,是否有一种简单/有效的方法将“当前解决方案日期”转换为如下所示的“预期输出”?我曾想过使用regex或string方法来清理Solr日期,但如果Python中有一种方法可以从Solr转换这些日期,那就太好了 当前解决方案日期: '2020-01-21T12:23:54.625Z' 所需输出(采用日期时间模块格式): 这里有一个从字符串到datetime对象再到字符串的快速往返过程,包括两个选项。希望这能让你走 字符串→ 日期时间(保持微秒) 日期时间→ 字符串(微秒) 如果您需要特定的精度,例

是否有一种简单/有效的方法将“当前解决方案日期”转换为如下所示的“预期输出”?我曾想过使用regex或string方法来清理Solr日期,但如果Python中有一种方法可以从Solr转换这些日期,那就太好了

当前解决方案日期:

'2020-01-21T12:23:54.625Z'
所需输出(采用
日期时间
模块格式):


这里有一个从字符串到datetime对象再到字符串的快速往返过程,包括两个选项。希望这能让你走

字符串→ 日期时间(保持微秒)

日期时间→ 字符串(微秒)


如果您需要特定的精度,例如毫秒,您可能还需要查看datetime.isoformat的kwarg。由于您不希望输出中有任何UTC偏移量规范,您可以只剥离
Z
,解析并调用我猜您是否知道如何将所需的输出转换回solr格式?(这是我“维切维萨”问题的一部分)。谢谢:)在你的例子中,你忽略了毫秒-对吗?毫秒可以忽略,是的(除非solr对此提出问题)好的,我在回答中使用了
。替换(微秒=0)
;你可以随时移除它,让它们留在里面。但请注意,Python将显示微秒(6位数)。将这些剥离到毫秒是另一个迂回;-)

'2020-01-21 12:23:54' 
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)
# 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