如何在python中获取当前日期时间的字符串格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3316882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get a string format of the current date time, in python?
提问by TIMEX
For example, on July 5, 2010, I would like to calculate the string
例如,在 2010 年 7 月 5 日,我想计算字符串
July 5, 2010
How should this be done?
这应该怎么做?
采纳答案by Dave Webb
You can use the datetimemodulefor working with dates and times in Python. The strftimemethodallows you to produce string representation of dates and times with a format you specify.
您可以使用该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'
回答by P?r Wieslander
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%B %d, %Y")
'July 23, 2010'
回答by Pieter
#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
1:test-2018-02-14_16:40:52.txt
2a: March 04, 2018
2a:2018 年 3 月 4 日
2b: March 04, 2018
2b:2018 年 3 月 4 日
3: Today is 2018-11-11 yay
3:今天是 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
https://docs.python.org/3/library/string.html#formatexamples
回答by scope
If you don't care about formatting and you just need some quick date, you can use this:
如果你不关心格式,你只需要一些快速的约会,你可以使用这个:
import time
print(time.ctime())

