簡體   English   中英

如何在Python中將日期時間字符串中的時間從24:00轉換為00:00?

[英]How can I convert the time in a datetime string from 24:00 to 00:00 in Python?

我有很多日期字符串,如Mon, 16 Aug 2010 24:00:00 ,其中一些是00-23小時格式,其中一些是01-24小時格式。 我想獲得它們的日期對象列表,但是當我嘗試將示例字符串轉換為日期對象時,我必須將它從Mon, 16 Aug 2010 24:00:00Tue, 17 Aug 2010 00:00:00 什么是最簡單的方法?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM