ISO 8601 日期时间格式:将 11:05:14 PM 解析为 23:05:14

ISO 8601 datetime format: parse 11:05:14 PM into 23:05:14

我目前正在获取 ISO 格式,但我不确定如何获取 ISO (8601) 格式。

当我将以下日期 08/10/2015 11:05:14 PM 转换为 ISO 格式时,我得到 2015-08-10T11:05:14+0000

理想情况下我应该得到 2015-08-10T23:05:14+0000

将日期编辑为 iso 格式的行是:

new[3] = datetime.strptime(new[3], "%m/%d/%Y %H:%M:%S %p").isoformat() + '+0000'

代码:

from tempfile import NamedTemporaryFile
from datetime import datetime
from shutil import move
from operator import itemgetter
import csv
from pathlib import Path


def change_file(in_file, cols):
    with open(in_file) as f, NamedTemporaryFile("w", dir=".", delete=False) as tmp:
        r = csv.reader(f)
        wr = csv.writer(tmp)
        count = 0
        for row in r:
            if count == 0:
                new = []
                for x in itemgetter(*cols)(row):
                    new.append(x.lstrip())
                wr.writerow(new)
                count += 1
                continue
            if row != '\n':
                new = []
                print(row)

                for x in itemgetter(*cols)(row):
                    new.append(x.lstrip())
                new[3] = datetime.strptime(new[3], "%m/%d/%Y %H:%M:%S %p").isoformat() + '+0000'
                print(new)
                wr.writerow(new)
        move(tmp.name, in_file)

for fle in Path('./BM').glob('**/*/cplt.csv'):
    print(fle)
    change_file(str(fle), (6, 2, 1, 0, 5))

输入格式究竟如何?

当我将您的格式字符串更改为 %m/%d/%y %H:%M:%S 时,以下

print datetime.strptime('08/10/15 23:05:14', '%m/%d/%y %H:%M:%S').isoformat() + '+0000'

给出正确的结果:

2015-08-10T23:05:14+0000

编辑

感谢您提供更多信息,如果您只需将 %H 替换为 %I:

,它应该可以工作
 print datetime.strptime('8/10/2015 11:05:14 PM', '%m/%d/%Y %I:%M:%S %p').isoformat() + '+0000'

来自datetime docs

%I - Hour (12-hour clock) as a zero-padded decimal number.

只有 %I 才会考虑 am/pm 部分。

当你使用%p指令时,你应该使用%I格式来解析小时。

来自文档:

When used with the strptime() method, the %p directive only affects the output hour field if the %I directive is used to parse the hour.