Python 格式化时间为 %d-%m-%y
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17245612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Formatting Time as %d-%m-%y
提问by user2341103
am trying to print orig_time as 6/9/2013 and running into following error..can anyone provide inputs on what is wrong here
我正在尝试将 orig_time 打印为 6/9/2013 并遇到以下错误..任何人都可以提供有关此处错误的输入
Code:
代码:
orig_time="2013-06-09 00:00:00"
Time=(orig_time.strftime('%m-%d-%Y'))
print Time
Error:-
错误:-
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'
回答by Ashwini Chaudhary
You cannot use strftimeon a string as it is not a method of string, one way to do this is by using the datetimemodule:
您不能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')
Now you can use either string formatting:
现在您可以使用任一字符串格式:
>>> "{}/{}/{}".format(d.month,d.day,d.year)
'6/9/2013'
or datetime.datetime.strftime:
>>> d.strftime('%m-%d-%Y')
'06-09-2013'
回答by Joran Beasley
>>> import time
>>> time.strftime("%m-%d-%y",time.strptime("2013-06-09 00:00:00","%Y-%m-%d %H:%M:%S"))
'06-09-13'
but its more of a pain to remove leading zeros ... If you need that use the other answer
但删除前导零更痛苦......如果你需要使用其他答案
also its unclear what you want, since your title says one thing (and your format string), but it does not match what you say is your expected output in the question
也不清楚你想要什么,因为你的标题说了一件事(和你的格式字符串),但它不符合你所说的是你在问题中的预期输出
回答by Tomy Ariswara
import time
orig_time="2013-06-09 00:00:00"
Time= time.strftime(orig_time, '%m-%d-%Y')
print Time

