将字典时间戳键值对转换为日期时间

Convert dictionary timestamp key-value pairs into datetime

我有一个字典,其中有一个存储为键值对的时间戳:

timestamp_info = {
    'day': 8, 'fold': 0, 'hour': 0,
    'max': {'day': 31, 'fold': 0,'hour': 23},
    'microsecond': 639000, 'minute': 17, 'month': 10, 'second': 35, 'year': 2021
}

我正在尝试从字典中获取时间戳并转换为 datetime.datetime 时间戳格式。我尝试了以下但它不起作用,因为它要求 str(确切的错误是:“strptime() 参数 1 必须是 str,而不是 dict”):

result = datetime.datetime.strptime(timestamp_info, "%Y-%m-%d %H:%M:%S")

我希望将此结果与 datetime.datetime.now 进行比较,并计算当前时间戳和结果之间的秒数差异,这就是我需要时间戳格式的原因。

您可以提取指定格式的时间戳的各个部分,并将它们拼接成一个字符串:

timestamp_info = {
    'day':8, 'fold':0,'hour':0, 'max':{'day':31, 'fold':0,'hour':23},
    'microsecond':639000,'minute':17,'month':10,'second':35, 'year':2021
}

year = str(timestamp_info['year'])
month = str(timestamp_info['month'])
day = str(timestamp_info['day'])
hour = str(timestamp_info['hour'])
minute = str(timestamp_info['minute'])
second = str(timestamp_info['second'])
timestamp = '-'.join([year, month, day]) + ' ' + ':'.join([hour, minute, second])

result = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")

这导致:

2021-10-08 00:17:35

已经展示了如何构建一个字符串,然后您可以使用 strptime() 解析该字符串。或者,您可以将值直接传递给 datetime():

timestamp_info = {
    'day':8, 'fold':0,'hour':0, 'max':{'day':31, 'fold':0,'hour':23},
    'microsecond':639000,'minute':17,'month':10,'second':35, 'year':2021
}

year = timestamp_info['year']
month = timestamp_info['month']
day = timestamp_info['day']
hour = timestamp_info['hour']
minute = timestamp_info['minute']
second = timestamp_info['second']

result = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second)

或者您可以通过删除 datetime 不需要的属性来更简洁地完成此操作:

timestamp_info = {
    'day':8, 'fold':0,'hour':0, 'max':{'day':31, 'fold':0,'hour':23},
    'microsecond':639000,'minute':17,'month':10,'second':35, 'year':2021
}

del timestamp_info['fold']
del timestamp_info['max']

result = datetime.datetime(**timestamp_info)