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

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

 July 5, 2010

应该怎么做?

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

 July 5, 2010

How should this be done?


回答 0

您可以使用该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'

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.

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

回答 1

#python3

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

d = datetime.datetime.now()
print( "2a: {:%B %d, %Y}".format(d))

# see the f" to tell python this is a f string, no .format
print(f"2b: {d:%B %d, %Y}")

print(f"3: Today is {datetime.datetime.now():%Y-%m-%d} yay")

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

2a:2018年3月4日

2b:2018年3月4日

3:今天是2018-11-11


描述:

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

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

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

#python3

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

d = datetime.datetime.now()
print( "2a: {:%B %d, %Y}".format(d))

# see the f" to tell python this is a f string, no .format
print(f"2b: {d:%B %d, %Y}")

print(f"3: Today is {datetime.datetime.now():%Y-%m-%d} yay")

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

2a: March 04, 2018

2b: March 04, 2018

3: Today is 2018-11-11 yay


Description:

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

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

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


回答 2

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

回答 3

如果您不关心格式,只需要一些快速日期,则可以使用以下方法:

import time
print(time.ctime())

If you don’t care about formatting and you just need some quick date, you can use this:

import time
print(time.ctime())

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。