所以我试图制作一个时间解析器,将3次时间格式中的1次转换为dd-mm-yy(28-sept-20。
这三者单独工作都很好,但当它们结合在一起时就不起作用了。
from datetime import datetime
def time_parser(self, time):
try:
start_period_obj = datetime.strptime(time, "%Y-%m-%dT%H:%M:%S.%fZ")
print('variation 1 is what was used')
except:
start_period_obj = datetime.strptime(time, "%Y-%m-%dT%H:%M:%SZ")
print('variation 2 is what was used')
else:
start_period = time.split('T')[0]
start_period_obj = datetime.strptime(time, "%Y-%m-%d")
print('variation 3 is what was used')
finally:
start_period = time.split('T')[0]
start_period_obj = datetime.strptime(time, "%Y-%m-%d")
print('variation 4 is what was used')
new_format = start_period_obj.strftime("%d-%b-%y")
print('The start date is')
print(new_format)
return new_format
#the time formats
start_time1 = "2020-08-28T13:42:00.298363-05:00"
start_time2 = "2020-09-03T16:33:47.289147Z"
start_time3 = "2020-09-01T00:00:00-05:00"
start_time4 = "2020-09-03T16:33:47Z"
time_parser(start_time1)
输出为
Traceback (most recent call last):
File "time conveter.py", line 33, in <module>
time_parser(start_time1)
TypeError: time_parser() missing 1 required positional argument: 'time'
我想要的输出是
dd-mm-yy
请帮助
首先,如果将self
传递给函数,这通常意味着它是一个类方法,self是类实例。在这里,情况似乎并非如此。您之所以会出现错误,是因为您只向函数传递了一个参数,即self和time。如果您想在类之外使用函数,请删除self。
此外,如果您想测试不同的格式来解析时间字符串,最好将它们包装在try/except中运行的循环中,例如,如图所示。
最后,如果这些都是你遇到的时间字符串格式,你可以用fromisoformat
(docs(:很好地解析它们
from datetime import datetime
fmts = ("2020-08-28T13:42:00.298363-05:00",
"2020-09-03T16:33:47.289147Z",
"2020-09-01T00:00:00-05:00",
"2020-09-03T16:33:47Z")
for f in fmts:
print(datetime.fromisoformat(f.replace('Z', '+00:00'))) # account for Z=zulu=UTC
# 2020-08-28 13:42:00.298363-05:00
# 2020-09-03 16:33:47.289147+00:00
# 2020-09-01 00:00:00-05:00
# 2020-09-03 16:33:47+00:00
所以我结合了你的一些回复,得到了这个。到目前为止,它还可以转换任何时间格式。
def time_parser(time):
start_period = time.split('T')[0]
start_period_obj = datetime.strptime(start_period, "%Y-%m-%d")
new_format = start_period_obj.strftime("%d-%b-%y")
print('The converted date is')
print(new_format)
print("_______________________")
return new_format