Python 将一种格式的日期转换为另一种格式
我有一个日期,格式为“%Y-%M-%d”,例如“2017-08-01”,我想将其转换为“%M-%d-%Y”格式,例如“8-1-2017” 不幸的是,我发现只有php中有相关的例子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')
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.