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

143

例如,我想要计算2010年7月5日这个字符串。

 July 5, 2010

应该如何做?

6个回答

252
你可以使用 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'

51
#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

https://docs.python.org/3/library/datetime.html


print(f"3)中,f代表格式化字符串。 - Lei Yang
@lei-yang 这里有一个解释:https://realpython.com/python-f-strings/ 它将字符串标记为f字符串,然后Python查找其中的包含代码/变量的{ },并将内容放入字符串中。这是最新的Python3.6字符串格式添加。 - Pieter
1
本页面底部列出了占位符(如%B)及其所代表的含义,详见https://docs.python.org/3/library/datetime.html。 - James Toomey

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

12

如果您不关心格式,只需要一些快速的日期信息,您可以使用以下内容:

import time
print(time.ctime())

2

使用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


1

简单

# 15-02-2023
datetime.datetime.now().strftime("%d-%m-%Y")

对于这个问题,请使用“2010年7月5日”

# July 5, 2010
datetime.datetime.now().strftime("%B %d, %Y")

这不是问题中要求的格式,是吗? - Moritz Ringler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接