如何在python中获取当前日期时间的字符串格式?

问题描述:

例如,2010年7月5日,我想计算字符串如何在python中获取当前日期时间的字符串格式?

July 5, 2010 

应该如何进行?

您可以使用datetime module在Python中处理日期和时间。 strftime method允许您使用您指定的格式生成日期和时间的字符串表示。

>>> import datetime 
>>> datetime.date.today().strftime("%B %d, %Y") 
'July 23, 2010' 
>>> datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y") 
'10:36AM on July 23, 2010' 

>>> import datetime 
>>> now = datetime.datetime.now() 
>>> now.strftime("%B %d, %Y") 
'July 23, 2010' 

#python3 

import datetime 
print(
    '1: test-{date:%Y-%m-%d %H:%M:%S}.txt'.format(date=datetime.datetime.now()) 
    ) 
d = datetime.datetime.now() 
print('2: {:%B %d, %Y}'.format(d)) 

1:测试2018-02-14_16:40:52.txt

2:2018年3月4日


描述:

使用新的stri ng格式将值注入到placeholder {}的字符串中,value是当前时间。

然后,不要仅仅将原始值显示为{},请使用格式化来获取正确的日期格式。

https://docs.python.org/3/library/string.html#formatexamples

+0

您的答案被标记为低质量,因为它只是代码。尝试更深入地解释你的答案。 – 2018-02-14 05:36:20