如何在Python中将datetime字符串中的时间从24:00转换为00:00? [英] How can I convert the time in a datetime string from 24:00 to 00:00 in Python?

查看:1261
本文介绍了如何在Python中将datetime字符串中的时间从24:00转换为00:00?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多日期字符串,如 Mon,2010年8月16日24:00:00 ,其中一些位于 00-23 小时格式,其中一些在 01-24 小时格式。我想得到他们的日期对象的列表,但是当我尝试将示例字符串转换为日期对象时,我必须将其转换为 Mon,2010年8月16日24:00:00 星期二,2010年8月17日00:00:00 。什么是最简单的方法?

I have a lot of date strings like Mon, 16 Aug 2010 24:00:00 and some of them are in 00-23 hour format and some of them in 01-24 hour format. I want to get a list of date objects of them, but when I try to transform the example string into a date object, I have to transform it from Mon, 16 Aug 2010 24:00:00 to Tue, 17 Aug 2010 00:00:00. What is the easiest way?

推荐答案

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

由于你说你有很多修复,你应该定义一个函数:

Since you say you have a lot of these to fix, you should define a function:

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

这篇关于如何在Python中将datetime字符串中的时间从24:00转换为00:00?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆