Python 如何通过计算将字符串转换为日期?

Python 如何通过计算将字符串转换为日期?,python,Python,我在解析日期块(5小时前)或(14分钟前)后得到 如何获取日期,如:01.21.21 3:31,我不知道如何使用此类数据获取日期。对于传入的日期数据,这是一种不寻常的结构,但我建议尝试以下内容: # import the requisite modules from datetime import datetime, timedelta # sample string, you could loop through the data you have date = "5 hours

我在解析日期块(5小时前)或(14分钟前)后得到


如何获取日期,如:01.21.21 3:31,我不知道如何使用此类数据获取日期。

对于传入的日期数据,这是一种不寻常的结构,但我建议尝试以下内容:

# import the requisite modules
from datetime import datetime, timedelta

# sample string, you could loop through the data you have
date = "5 hours ago"

# splits the string into words (this assumes a predictable pattern in data)
words = date.split(" ")

# conditional logic to determine the right amount of time to subtract
if words[1] == 'hours':
  date = datetime.now() - timedelta(hours=int(words[0]))
elif words[1] == 'minutes':
  date = datetime.now() - timedelta(minutes=int(words[0]))

# print(date)
# 2021-01-20 17:05:08.161174

希望这有帮助!如果您有任何问题,请告诉我

您可以添加一个更详细的输入示例吗?我有一个日期列表:1)5分钟前,2)7小时前,3)51秒前,等等,不超过24小时。是否有可能像01.21.21 3:31那样转换到日期?因此,它们指的是一个特定的时间点:它是什么?你必须知道它,否则任何时候你运行脚本,你会得到不同的结果。非常感谢,它工作!每次运行此脚本时,即使输入相同,也会得到不同的结果。可能应该使用参考时间戳更改
datetime.now()