我有一个已编写的脚本,我需要更改日期,当脚本运行时输出此消息
output_messaging("*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON " +
str(datetime.date.today().day) + "/" + str(datetime.date.today().month) + "/" +
str(datetime.date.today().year) + " AT " + str(datetime.datetime.now().hour) + ':' +
str(datetime.datetime.now().minute) + ':' + str(datetime.datetime.now().second) + " ***\n\n")
哪个给出了
*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON 20/2/2012 AT 18:3 ***
我需要转换为
的日期 20/Feb/2012
,我该怎么做?
答案 0 :(得分:2)
output_messaging("*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON {0:%d/%b/%Y} AT {0:%H:%M} ***".format(datetime.datetime.now()))
打印
*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON 28/Feb/2012 AT 17:41 ***
答案 1 :(得分:2)
使用strftime
- 这比做一堆自定义连接更容易。有一个格式约定表here。
>>> s = "*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON "\
... "%d/%b/%y AT %H:%M:%S ***\n\n"
>>> datetime.datetime.now().strftime(s)
'*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON 28/Feb/12 AT 11:44:03 ***\n\n'
正如eumiro的回答所示,您也可以使用稍微修改过的格式字符串来反转上述调用,如下所示:
>>> s = "*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON "\
... "{0:%d/%b/%y} AT {0:%H:%M:%S} ***\n\n"
>>> s.format(datetime.datetime.now())
'*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON 28/Feb/12 AT 13:41:10 ***\n\n'
这是有效的,因为format
只是调用__format__
对象的(令人震惊的记录不足)datetime.datetime
方法。例如:
>>> datetime.datetime.now().__format__('The current month is %B')
'The current month is February'
这适用于其他类型:
>>> (16).__format__('x')
'10'
有关__format__
的更多信息,请参阅PEP 3101
答案 2 :(得分:1)
>>> from datetime import date
>>> day = date.today()
>>> day.strftime('%d/%b/%y')
'28/Feb/12'
答案 3 :(得分:0)
import datetime
print datetime.datetime.now().strftime('%d/%b/%Y')
# 28/Feb/2012