如何在python中将以下字符串日期转换为日期格式。
input:
date='15-MARCH-2015'
expected output:
2015-03-15
我尝试使用datetime.strftime
和datetime.strptime
。它不接受这种格式。
发布于 2015-06-13 21:58:02
您可以使用适当格式的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
发布于 2015-06-14 00:45:38
datetime
模块将在这里为您提供帮助。首先使用strptime
将字符串转换为datetime
对象,然后使用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'
符合您想要的格式。
发布于 2015-06-14 00:52:48
您可以使用easy_date来简化这一过程:
import date_converter
converted_date = date_converter.string_to_string('15-MARCH-2015', '%d-%B-%Y', '%Y-%m-%d')
https://stackoverflow.com/questions/30819423
复制相似问题