![](/img/trans.png)
[英]Python: How to compare date string in ISO 8601 format with current time
[英]How do I get a string format of the current date time, in python?
例如,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:2018 年 3 月 4 日
3:今天是 2018-11-11 耶
4:时区感知时间:2022-05-05T09:04:24+0000
描述:
使用新的字符串格式将 value 注入到占位符 {} 的字符串中,value 是当前时间。
然后,不只是将原始值显示为 {},而是使用格式化来获取正确的日期格式。
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())
带时间模块:
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'
更多格式: www.tutorialspoint.com
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.