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

时间:2022-09-18 07:28:53

For example, on July 5, 2010, I would like to calculate the string

例如,在2010年7月5日,我想计算字符串

 July 5, 2010

How should this be done?

该怎么做?

3 个解决方案

#1


146  

You can use the datetime module for working with dates and times in Python. The strftime method allows you to produce string representation of dates and times with a format you specify.

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

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

#2


17  

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

#3


8  

#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: test-2018-02-14_16:40:52.txt

1:test-2018-02-14_16:40:52.txt

2: March 04, 2018

2:2018年3月4日


Description:

描述:

Using the new string format to inject value into a string at placeholder {}, value is the current time.

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

Then rather than just displaying the raw value as {}, use formating to obtain the correct date format.

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

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

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

#1


146  

You can use the datetime module for working with dates and times in Python. The strftime method allows you to produce string representation of dates and times with a format you specify.

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

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

#2


17  

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

#3


8  

#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: test-2018-02-14_16:40:52.txt

1:test-2018-02-14_16:40:52.txt

2: March 04, 2018

2:2018年3月4日


Description:

描述:

Using the new string format to inject value into a string at placeholder {}, value is the current time.

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

Then rather than just displaying the raw value as {}, use formating to obtain the correct date format.

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

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

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