我试图将 orig_time 打印为 6/9/2013 并遇到以下错误..任何人都可以提供有关此处错误的信息
代码:
orig_time="2013-06-09 00:00:00"
Time=(orig_time.strftime('%m-%d-%Y'))
print Time
错误:-
Traceback (most recent call last):
File "date.py", line 2, in <module>
Time=(orig_time.strftime('%m-%d-%Y'))
AttributeError: 'str' object has no attribute 'strftime'
最佳答案
您不能在字符串上使用 strftime
,因为它不是字符串的方法,一种方法是使用 datetime
模块:
>>> from datetime import datetime
>>> orig_time="2013-06-09 00:00:00"
#d is a datetime object
>>> d = datetime.strptime(orig_time, '%Y-%m-%d %H:%M:%S')
现在您可以使用任一字符串格式:
>>> "{}/{}/{}".format(d.month,d.day,d.year)
'6/9/2013'
>>> d.strftime('%m-%d-%Y')
'06-09-2013'
关于python - 将时间格式化为 %d-%m-%y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17245612/