我有2个变量。一个是字符串格式的日期时间,另一个是 datetime.datetime 格式的日期时间。
例如 -
2021-09-06T07:58:19.032Z # string
2021-09-05 14:58:10.209675 # datetime.datetime
我想以秒为单位找出这 2 次之间的差异。我认为我们需要在日期时间中同时拥有两者,然后才能进行减法运算。我很难将字符串转换为日期时间。有人可以帮忙吗。
您可以将字符串转换为datetime
对象strptime()
给定日期的示例:
from datetime import datetime
# Assuming this is already a datetime object in your code, you don't need this part
# I needed this part to be able to use it as a datetime object
date1 = datetime.strptime("2021-09-05 14:58:10.209675", "%Y-%m-%d %H:%M:%S.%f")
## The part where the string is converted to datetime object
# Since the string has "T" and "Z", we will have to remove them before we convert
formatted = "2021-09-06T07:58:19.032Z".replace("T", " ").replace("Z", "")
>>> 2021-09-06 07:58:19.032
# Finally, converting the string
date2 = datetime.strptime(formatted, "%Y-%m-%d %H:%M:%S.%f")
# Now date2 variable is a datetime object
# Performing a simple operation
print(date1 - date2)
>>> -1 day, 6:59:51.177675
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句