How do I convert date to Day/Month/Year (20/Jan/2012) in python
我有一个脚本已经写了,我需要更改运行该脚本的日期,它将输出此消息
1 2 3 4 5 6 | 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) +" *** ") |
哪个给了
1 | *** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON 20/2/2012 AT 18:3 *** |
号
我需要把日期改成
使用
1 2 3 4 5 6 7 8 | >>> s ="*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON"\ ... "%d/%b/%y AT %H:%M:%S *** " >>> datetime.datetime.now().strftime(s) '*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON 28/Feb/12 AT 11:44:03 *** ' |
如Eumiro的答案所示,您还可以使用稍微修改过的格式字符串来反转上述调用,如下所示:
1 2 3 4 5 6 7 8 | >>> s ="*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON"\ ... "{0:%d/%b/%y} AT {0:%H:%M:%S} *** " >>> s.format(datetime.datetime.now()) '*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON 28/Feb/12 AT 13:41:10 *** ' |
。
这是因为
1 2 | >>> datetime.datetime.now().__format__('The current month is %B') 'The current month is February' |
。
这也适用于其他类型:
1 2 | >>> (16).__format__('x') '10' |
有关
1 | output_messaging("*** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON {0:%d/%b/%Y} AT {0:%H:%M} ***".format(datetime.datetime.now())) |
号
印刷品
1 | *** DATA REFRESH FOR STREETWORKS DATA EXECUTED ON 28/Feb/2012 AT 17:41 *** |
有关日期时间格式的详细信息
1 2 3 4 | >>> from datetime import date >>> day = date.today() >>> day.strftime('%d/%b/%y') '28/Feb/12' |
。
1 2 3 | import datetime print datetime.datetime.now().strftime('%d/%b/%Y') # 28/Feb/2012 |