gpt4 book ai didi

python - 将字符串列表转换为日期时间

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:37 24 4
gpt4 key购买 nike

我正在尝试将字符串列表转换为日期时间。

这是我正在处理的数据的示例:
x = ['59:55:00', '59:55:00', '59:58:00', '1:00:02', '1:00:05', '1:01 :26']

例如,该列表应该反射(reflect) 59 分 58 秒到 1 小时 0 分 5 秒。

我知道这是一种古怪的格式,但我正在玩我已经发牌的牌。一旦输入大于 59 分钟的值,我不确定如何处理数据。

我尝试使用:

from datetime import datetime
for i in x:
datetime_object = datetime.strptime(i, '%M:%S:%f')
print(datetime_object)

我的结果是:

1900-01-01 00:59:55
1900-01-01 00:59:55
1900-01-01 00:59:58
1900-01-01 00:01:00.020000
1900-01-01 00:01:00.050000
1900-01-01 00:01:01.260000

我想将我的输出保持在分钟和秒之间。例如 1:01:26 将是 00:61:26

所以我想要的输出看起来像这样:

1900-01-01 00:59:55
1900-01-01 00:59:55
1900-01-01 00:59:58
1900-01-01 00:60:02
1900-01-01 00:60:02
1900-01-01 00:61:26

非常感谢任何帮助或指导!

最佳答案

datetime.datetime 对象必须采用一定范围内的参数,即分钟必须在 059 之间。但是,您可以创建一个类来处理这种所需的行为。该类可以将输入转换为所需的时间戳格式,存储原始字符串,并提供 to_date 属性以将实际时间戳检索为 datetime.datetime 对象:

import datetime

class Minutes:
d = datetime.datetime.now()
def __init__(self, _str, _year = None):
self._val = _str
d = datetime.datetime.now()
self.year = _year if _year is not None else '-'.join(str(getattr(d, i)) for i in ['year', 'month', 'day'])
@property
def to_date(self):
return datetime.datetime(*map(int, self.year.split('-')), *map(int, str(self).split(':')))
def __str__(self):
_h, _m, _s = map(int, self._val.split(':'))
h, m, s = 0 if _h else _h, _m+(_h*60) if _h else _m, _s
return f'{self.year} '+':'.join(str(i).zfill(2) for i in [h, m, s])
def __repr__(self):
return str(self)

x = ['59:55:00', '59:55:00', '59:58:00', '1:00:02', '1:00:05', '1:01:26']
new_x = [Minutes(i, '1900-01-01') for i in x]

输出:

[1900-01-01 00:3595:00, 
1900-01-01 00:3595:00,
1900-01-01 00:3598:00,
1900-01-01 00:60:02,
1900-01-01 00:60:05,
1900-01-01 00:61:26]

关于python - 将字符串列表转换为日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54384416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com