如何在python中将日期转换为日/月/年(2012年1月20日)

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 ***

我需要把日期改成

20/Feb/2012我该怎么做?


使用strftime来实现这一点——这比进行一系列自定义连接要容易得多。这里有一个格式化约定表。

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 ***

'

这是因为format简单地调用了datetime.datetime对象的__format__方法(文档记录不足,令人震惊)。例如:

1
2
>>> datetime.datetime.now().__format__('The current month is %B')
'The current month is February'

这也适用于其他类型:

1
2
>>> (16).__format__('x')
'10'

有关__format__的更多信息,请参阅PEP 3101。


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