[英]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.