问题:仅在Python中将datetime对象转换为日期字符串

datetime在Python 中将日期字符串转换为对象时,我看到了很多东西,但是我想采用另一种方法。
我有

datetime.datetime(2012, 2, 23, 0, 0)

我想将其转换为类似的字符串'2/23/2012'

I see a lot on converting a date string to an datetime object in Python, but I want to go the other way.
I’ve got

datetime.datetime(2012, 2, 23, 0, 0)

and I would like to convert it to string like '2/23/2012'.


回答 0

您可以使用strftime来帮助您设置日期格式。

例如,

import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t.strftime('%m/%d/%Y')

将生成:

'02/23/2012'

有关格式化的更多信息,请参见此处

You can use strftime to help you format your date.

E.g.,

import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t.strftime('%m/%d/%Y')

will yield:

'02/23/2012'

More information about formatting see here


回答 1

datedatetime对象(以及对象time)都支持一种迷你语言来指定output,并且有两种访问它的方法:

  • 直接的方法调用:dt.strftime('format here'); 和
  • 新格式方法: '{:format here}'.format(dt)

因此,您的示例可能如下所示:

dt.strftime('%m/%d/%Y')

要么

'{:%m/%d/%Y}'.format(dt)

为了完整起见:您还可以直接访问对象的属性,但随后只能获取数字:

'%s/%s/%s' % (dt.month, dt.day, dt.year)

学习迷你语言所花的时间是值得的。


作为参考,以下是迷你语言中使用的代码:

  • %a 工作日为语言环境的缩写名称。
  • %A 工作日为语言环境的全名。
  • %w 以十进制数表示的工作日,其中0是星期日,6是星期六。
  • %d 以零填充的十进制数字表示月份中的一天。
  • %b 月作为语言环境的缩写名称。
  • %B 月作为语言环境的全名。
  • %m 以零填充的十进制数字表示的月份。01,…,12
  • %y 无世纪的年份,为零填充的十进制数字。00,…,99
  • %Y 以世纪作为十进制数字的年份。1970、1988、2001、2013
  • %H 小时(24小时制),为补零的十进制数字。00,…,23
  • %I 小时(12小时制),为零填充的十进制数字。01,…,12
  • %p 相当于AM或PM的语言环境。
  • %M 分钟,为零填充的十进制数字。00,…,59
  • %S 第二个为零填充的十进制数。00,…,59
  • %f 微秒,十进制数字,在左侧补零。000000,…,999999
  • %z UTC偏移量,格式为+ HHMM或-HHMM(如果为天真则为空),+ 0000,-0400,+ 1030
  • %Z 时区名称(如果是天真则为空),UTC,EST,CST
  • %j 一年中的一天,为零填充的十进制数字。001,…,366
  • %U 一年中的星期号(星期日是第一个),以零填充的十进制数表示。
  • %W 一年中的星期数(星期一为第一位),以十进制数表示。
  • %c 语言环境的适当日期和时间表示。
  • %x 语言环境的适当日期表示形式。
  • %X 语言环境的适当时间表示形式。
  • %% 文字“%”字符。

date and datetime objects (and time as well) support a mini-language to specify output, and there are two ways to access it:

  • direct method call: dt.strftime('format here'); and
  • new format method: '{:format here}'.format(dt)

So your example could look like:

dt.strftime('%m/%d/%Y')

or

'{:%m/%d/%Y}'.format(dt)

For completeness’ sake: you can also directly access the attributes of the object, but then you only get the numbers:

'%s/%s/%s' % (dt.month, dt.day, dt.year)

The time taken to learn the mini-language is worth it.


For reference, here are the codes used in the mini-language:

  • %a Weekday as locale’s abbreviated name.
  • %A Weekday as locale’s full name.
  • %w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
  • %d Day of the month as a zero-padded decimal number.
  • %b Month as locale’s abbreviated name.
  • %B Month as locale’s full name.
  • %m Month as a zero-padded decimal number. 01, …, 12
  • %y Year without century as a zero-padded decimal number. 00, …, 99
  • %Y Year with century as a decimal number. 1970, 1988, 2001, 2013
  • %H Hour (24-hour clock) as a zero-padded decimal number. 00, …, 23
  • %I Hour (12-hour clock) as a zero-padded decimal number. 01, …, 12
  • %p Locale’s equivalent of either AM or PM.
  • %M Minute as a zero-padded decimal number. 00, …, 59
  • %S Second as a zero-padded decimal number. 00, …, 59
  • %f Microsecond as a decimal number, zero-padded on the left. 000000, …, 999999
  • %z UTC offset in the form +HHMM or -HHMM (empty if naive), +0000, -0400, +1030
  • %Z Time zone name (empty if naive), UTC, EST, CST
  • %j Day of the year as a zero-padded decimal number. 001, …, 366
  • %U Week number of the year (Sunday is the first) as a zero padded decimal number.
  • %W Week number of the year (Monday is first) as a decimal number.
  • %c Locale’s appropriate date and time representation.
  • %x Locale’s appropriate date representation.
  • %X Locale’s appropriate time representation.
  • %% A literal ‘%’ character.

回答 2

另外一个选项:

import datetime
now=datetime.datetime.now()
now.isoformat()
# ouptut --> '2016-03-09T08:18:20.860968'

Another option:

import datetime
now=datetime.datetime.now()
now.isoformat()
# ouptut --> '2016-03-09T08:18:20.860968'

回答 3

您可以使用简单的字符串格式化方法:

>>> dt = datetime.datetime(2012, 2, 23, 0, 0)
>>> '{0.month}/{0.day}/{0.year}'.format(dt)
'2/23/2012'
>>> '%s/%s/%s' % (dt.month, dt.day, dt.year)
'2/23/2012'

You could use simple string formatting methods:

>>> dt = datetime.datetime(2012, 2, 23, 0, 0)
>>> '{0.month}/{0.day}/{0.year}'.format(dt)
'2/23/2012'
>>> '%s/%s/%s' % (dt.month, dt.day, dt.year)
'2/23/2012'

回答 4

type-specific formatting 也可以使用:

t = datetime.datetime(2012, 2, 23, 0, 0)
"{:%m/%d/%Y}".format(t)

输出:

'02/23/2012'

type-specific formatting can be used as well:

t = datetime.datetime(2012, 2, 23, 0, 0)
"{:%m/%d/%Y}".format(t)

Output:

'02/23/2012'

回答 5

如果您正在寻找一种简单的方式来datetime进行字符串转换并可以省略格式。您可以将datetime对象转换为str,然后使用数组切片。

In [1]: from datetime import datetime

In [2]: now = datetime.now()

In [3]: str(now)
Out[3]: '2019-04-26 18:03:50.941332'

In [5]: str(now)[:10]
Out[5]: '2019-04-26'

In [6]: str(now)[:19]
Out[6]: '2019-04-26 18:03:50'

但是请注意以下几点。如果在这种情况下,AttributeError当其他解决方案上升时,None您将收到一个'None'字符串。

In [9]: str(None)[:19]
Out[9]: 'None'

If you looking for a simple way of datetime to string conversion and can omit the format. You can convert datetime object to str and then use array slicing.

In [1]: from datetime import datetime

In [2]: now = datetime.now()

In [3]: str(now)
Out[3]: '2019-04-26 18:03:50.941332'

In [5]: str(now)[:10]
Out[5]: '2019-04-26'

In [6]: str(now)[:19]
Out[6]: '2019-04-26 18:03:50'

But note the following thing. If other solutions will rise an AttributeError when the variable is None in this case you will receive a 'None' string.

In [9]: str(None)[:19]
Out[9]: 'None'

回答 6

通过直接使用日期时间对象的组件,可以将日期时间对象转换为字符串。

from datetime import date  

myDate = date.today()    
#print(myDate) would output 2017-05-23 because that is today
#reassign the myDate variable to myDate = myDate.month 
#then you could print(myDate.month) and you would get 5 as an integer
dateStr = str(myDate.month)+ "/" + str(myDate.day) + "/" + str(myDate.year)    
# myDate.month is equal to 5 as an integer, i use str() to change it to a 
# string I add(+)the "/" so now I have "5/" then myDate.day is 23 as
# an integer i change it to a string with str() and it is added to the "5/"   
# to get "5/23" and then I add another "/" now we have "5/23/" next is the 
# year which is 2017 as an integer, I use the function str() to change it to 
# a string and add it to the rest of the string.  Now we have "5/23/2017" as 
# a string. The final line prints the string.

print(dateStr)  

输出-> 5/23/2017

It is possible to convert a datetime object into a string by working directly with the components of the datetime object.

from datetime import date  

myDate = date.today()    
#print(myDate) would output 2017-05-23 because that is today
#reassign the myDate variable to myDate = myDate.month 
#then you could print(myDate.month) and you would get 5 as an integer
dateStr = str(myDate.month)+ "/" + str(myDate.day) + "/" + str(myDate.year)    
# myDate.month is equal to 5 as an integer, i use str() to change it to a 
# string I add(+)the "/" so now I have "5/" then myDate.day is 23 as
# an integer i change it to a string with str() and it is added to the "5/"   
# to get "5/23" and then I add another "/" now we have "5/23/" next is the 
# year which is 2017 as an integer, I use the function str() to change it to 
# a string and add it to the rest of the string.  Now we have "5/23/2017" as 
# a string. The final line prints the string.

print(dateStr)  

Output –> 5/23/2017


回答 7

您可以将日期时间转换为字符串。

published_at = "{}".format(self.published_at)

You can convert datetime to string.

published_at = "{}".format(self.published_at)

回答 8

字符串连接str.join可以用来构建字符串。

d = datetime.now()
'/'.join(str(x) for x in (d.month, d.day, d.year))
'3/7/2016'

String concatenation, str.join, can be used to build the string.

d = datetime.now()
'/'.join(str(x) for x in (d.month, d.day, d.year))
'3/7/2016'

回答 9

如果您还需要时间,请选择

datetime.datetime.now().__str__()

2019-07-11 19:36:31.118766在控制台中为我打印

If you want the time as well, just go with

datetime.datetime.now().__str__()

Prints 2019-07-11 19:36:31.118766 in console for me


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。