猜猜日期格式python

时间:2014-04-25 08:59:40

标签: python exception datetime strptime

我正在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)
'''

如果用户指定start_date或end_date,则应进行检查以确定日期是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)

这是一个很好的方法吗?我能以更好的方式查看我收到的日期吗? 谢谢!

1 个答案:

答案 0 :(得分:3)

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