在python中将字符串日期转换为日期格式?

时间:2015-06-13 13:53:00

标签: python date datetime

如何在python中将以下字符串日期转换为日期格式。

input:
date='15-MARCH-2015'

expected output:
2015-03-15

我尝试使用datetime.strftimedatetime.strptime。它不接受这种格式。

3 个答案:

答案 0 :(得分:8)

您可以使用datetime.strptime格式正确:

>>> datetime.strptime('15-MARCH-2015','%d-%B-%Y')
datetime.datetime(2015, 3, 15, 0, 0)

详细了解datetime.strptime和日期格式:https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

答案 1 :(得分:1)

datetime模块将在此为您提供帮助。首先使用datetime将字符串转换为strptime对象,然后使用strftime将此对象转换为所需的字符串格式:

from datetime import datetime
datetime.strftime(datetime.strptime('15-MARCH-2015','%d-%B-%Y'),'%Y-%m-%d')

将屈服:

'2015-03-15'

请注意,字符串格式'%d-%B-%Y'与您拥有的字符串一致,'%Y-%m-%d'符合您希望它的格式。

答案 2 :(得分:-1)

您可以使用easy_date轻松实现:

import date_converter
converted_date = date_converter.string_to_string('15-MARCH-2015', '%d-%B-%Y', '%Y-%m-%d')
相关问题