gpt4 book ai didi

python - 猜测python的日期格式

转载 作者:行者123 更新时间:2023-11-30 23:24:47 25 4
gpt4 key购买 nike

我正在 Python 模块中编写一个方法,试图让用户的生活变得更轻松。此方法实现了在该日历中创建事件。

def update_event(start_datetime=None, end_datetime=None, description=None):
'''
Args:
start_date: string datetime in the format YYYY-MM-DD or in RFC 3339
end_date: string datetime in the format YYYY-MM-DD or in RFC 3339
description: string with description (\n are transforrmed into new lines)
'''

如果用户指定开始日期或结束日期,则应进行检查以确定日期是采用 YYYY-MM-DD 格式还是日期时间 RFC 3339 格式。

if (start_date is not None):
# Check whether we have an date or datetime value
# Whole day events are represented as YYYY-MM-DD
# Other events are represented as 2014-04-25T10:47:00.000-07:00
whole_day_event = False
try:
new_start_time = datetime.datetime.strptime(start_date,'YYYY-MM-DD')
# Here the event date is updated
try:
new_start_time = datetime.datetime.strptime(start_date,'%Y-%m-%dT%H:%M:%S%z')
#Here the event date is updated
except ValueError:
return (ErrorCodeWhatever)
except ValueError:
return (ErrorCodeWhatever)

这是一个好方法吗?我可以以更好的方式检查我收到的日期类型吗?谢谢!

最佳答案

dateutil.parser.parse可用于尝试将字符串解析为 datetime 对象。

from dateutil.parser import parse

def update_event(start_datetime=None, end_datetime=None, description=None):
if start_datetime is not None:
new_start_time = parse(start_datetime)

return new_start_time

d = ['23/04/2014', '24-04-2013', '25th April 2014']

new = [update_event(i) for i in d]

for date in new:
print(date)
# 2014-04-23 00:00:00
# 2013-04-24 00:00:00
# 2014-04-25 00:00:00

关于python - 猜测python的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23288610/

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