Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将一种格式的日期转换为另一种格式_Python_Datetime - Fatal编程技术网

Python 将一种格式的日期转换为另一种格式

Python 将一种格式的日期转换为另一种格式,python,datetime,Python,Datetime,我有一个日期,格式为“%Y-%M-%d”,例如“2017-08-01”,我想将其转换为“%M-%d-%Y”格式,例如“8-1-2017” 不幸的是,我发现只有php中有相关的例子 from datetime import datetime datetime.strptime("2017-08-01", '%Y-%m-%d').strftime('%m-%d-%y') datetime.strptime("2017-08-01", '%Y-%m-%d')

我有一个日期,格式为“%Y-%M-%d”,例如“2017-08-01”,我想将其转换为“%M-%d-%Y”格式,例如“8-1-2017”

不幸的是,我发现只有php中有相关的例子

from datetime import datetime
datetime.strptime("2017-08-01", '%Y-%m-%d').strftime('%m-%d-%y')

datetime.strptime("2017-08-01", '%Y-%m-%d')
#output
datetime.datetime(2017, 8, 1, 0, 0)

#output final
'08-01-17'
在第一部分中,您定义了日期对您的意义。换句话说,您正在将字符串转换为datetime类型实例。然后在第二部分中,您将按照您希望的方式格式化strftime

官方定义


为什么要使用正则表达式?还有其他python工具更能解析日期。例如,
datetime
我应该用“格式”这个词,我在title@orion24完成后,尝试对其进行更多实验,并从operator import itemgetter和
'-'.join(itemgetter(1,2,0)(s.split('-'))
中了解它,其中
s
是原始日期
date, datetime, and time objects all support a strftime(format) method, 
to create a string representing the time under the control of an explicit format string.

Conversely, the datetime.strptime() class method creates
a datetime object from a string representing a date and 
time and a corresponding format string.