例如,我想要计算2010年7月5日这个字符串。
July 5, 2010
应该如何做?
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'
#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")
#4: to make the time timezone-aware pass timezone to .now()
tz = datetime.timezone.utc
ft = "%Y-%m-%dT%H:%M:%S%z"
t = datetime.datetime.now(tz=tz).strftime(ft)
print(f"4: timezone-aware time: {t}")
1: test-2018-02-14_16:40:52.txt
2a: 2018年3月4日
2b: March 04, 2018
3: 今天是2018年11月11日,耶!
4: 时区感知时间:2022年5月5日T09:04:24+0000
描述:
使用新的字符串格式将值注入到占位符{}中,该值为当前时间。
然后,不仅仅显示原始值{},而是使用格式化来获取正确的日期格式。
https://docs.python.org/3/library/string.html#formatexamples
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%B %d, %Y")
'July 23, 2010'
如果您不关心格式,只需要一些快速的日期信息,您可以使用以下内容:
import time
print(time.ctime())
使用time模块:
import time
time.strftime("%B %d, %Y")
>>> 'July 23, 2010'
time.strftime("%I:%M%p on %B %d, %Y")
>>> '10:36AM on July 23, 2010'
For more formats: www.tutorialspoint.com
简单
# 15-02-2023
datetime.datetime.now().strftime("%d-%m-%Y")
对于这个问题,请使用“2010年7月5日”
# July 5, 2010
datetime.datetime.now().strftime("%B %d, %Y")
print(f"3)
中,f
代表格式化字符串。 - Lei Yang%B
)及其所代表的含义,详见https://docs.python.org/3/library/datetime.html。 - James Toomey