如何在Python中将日期时间字符串中的24:00转换为00:00?

11 投票
1 回答
6786 浏览
提问于 2025-04-16 02:51

我有很多日期字符串,比如 Mon, 16 Aug 2010 24:00:00,其中一些是 00-23 小时格式,另一些是 01-24 小时格式。我想把这些字符串转换成日期对象,但当我尝试把这个例子字符串转换成日期对象时,我需要把 Mon, 16 Aug 2010 24:00:00 转换成 Tue, 17 Aug 2010 00:00:00。有什么简单的方法吗?

1 个回答

11
import email.utils as eutils
import time
import datetime

ntuple=eutils.parsedate('Mon, 16 Aug 2010 24:00:00')
print(ntuple)
# (2010, 8, 16, 24, 0, 0, 0, 1, -1)
timestamp=time.mktime(ntuple)
print(timestamp)
# 1282017600.0
date=datetime.datetime.fromtimestamp(timestamp)
print(date)
# 2010-08-17 00:00:00
print(date.strftime('%a, %d %b %Y %H:%M:%S'))
# Tue, 17 Aug 2010 00:00:00
def standardize_date(date_str):
    ntuple=eutils.parsedate(date_str)
    timestamp=time.mktime(ntuple)
    date=datetime.datetime.fromtimestamp(timestamp)
    return date.strftime('%a, %d %b %Y %H:%M:%S')

print(standardize_date('Mon, 16 Aug 2010 24:00:00'))
# Tue, 17 Aug 2010 00:00:00

既然你说你有很多这样的需要修复的地方,那你应该定义一个函数:

撰写回答