[英]How do I turn a python datetime into a string, with readable format date?
t = e['updated_parsed']
dt = datetime.datetime(t[0],t[1],t[2],t[3],t[4],t[5],t[6]
print dt
>>>2010-01-28 08:39:49.000003
How do I turn that into a string?:我如何把它变成一个字符串?:
"January 28, 2010"
The datetime class has a method strftime. datetime类具有strftime方法。 The Python docs documents the different formats it accepts:
Python文档记录了它接受的不同格式:
For this specific example, it would look something like: 对于此特定示例,它看起来像:
my_datetime.strftime("%B %d, %Y")
Here is how you can accomplish the same using python's general formatting function... 这是使用python的常规格式化功能可以完成的工作...
>>>from datetime import datetime
>>>"{:%B %d, %Y}".format(datetime.now())
The formatting characters used here are the same as those used by strftime . 此处使用的格式字符与strftime使用的格式字符相同。 Don't miss the leading
:
in the format specifier. 不要错过格式说明符中的开头
:
。
Using format() instead of strftime() in most cases can make the code more readable, easier to write and consistent with the way formatted output is generated... 在大多数情况下,使用format()而非strftime()可使代码更具可读性,易于编写,并与格式化输出的生成方式保持一致...
>>>"{} today's date is: {:%B %d, %Y}".format("Andre", datetime.now())
Compare the above with the following strftime() alternative... 将以上内容与以下strftime()替代内容进行比较...
>>>"{} today's date is {}".format("Andre", datetime.now().strftime("%B %d, %Y"))
Moreover, the following is not going to work... 此外,以下内容将无法工作...
>>>datetime.now().strftime("%s %B %d, %Y" % "Andre")
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
datetime.now().strftime("%s %B %d, %Y" % "Andre")
TypeError: not enough arguments for format string
And so on... 等等...
from datetime import datetime
date_string = f'{datetime.now():%Y-%m-%d %H:%M:%S%z}'
very old question, i know. 我知道很老的问题。 but with the new f-strings (starting from python 3.6) there are fresh options.
但是有了新的f字符串 (从python 3.6开始),就有了新的选择。 so here for completeness:
因此,此处出于完整性考虑:
from datetime import datetime
dt = datetime.now()
# str.format
strg = '{:%B %d, %Y}'.format(dt)
print(strg) # July 22, 2017
# datetime.strftime
strg = dt.strftime('%B %d, %Y')
print(strg) # July 22, 2017
# f-strings in python >= 3.6
strg = f'{dt:%B %d, %Y}'
print(strg) # July 22, 2017
strftime()
and strptime()
Behavior explains what the format specifiers mean. strftime()
和strptime()
行为说明了格式说明符的含义。
阅读官方文档中的strfrtime 。
Python datetime object has a method attribute, which prints in readable format. Python datetime对象具有method属性,该属性以可读格式打印。
>>> a = datetime.now()
>>> a.ctime()
'Mon May 21 18:35:18 2018'
>>>
This is for format the date? 这是用于格式化的日期吗?
def format_date(day, month, year):
# {} betekent 'plaats hier stringvoorstelling van volgend argument'
return "{}/{}/{}".format(day, month, year)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.