我在Python中看到了很多关于将日期字符串转换为datetime对象的内容,但我想采用另一种方式。 我有

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

我想把它转换成'2/23/2012'这样的字符串。


当前回答

一种距离现在有多远的方法

通过传入参数li来支持不同的语言,这是一个对应的时间戳列表。

from datetime import datetime
from dateutil import parser

t1 = parser.parse("Tue May 26 15:14:45 2021")
t2 = parser.parse("Tue May 26 15:9:45 2021")
# 5min
t3 = parser.parse("Tue May 26 11:14:45 2021")
# 4h
t4 = parser.parse("Tue May 26 11:9:45 2021")
# 1day
t6 = parser.parse("Tue May 25 11:14:45 2021")
# 1day4h
t7 = parser.parse("Tue May 25 11:9:45 2021")
# 1day4h5min
t8 = parser.parse("Tue May 19 11:9:45 2021")
# 1w
t9 = parser.parse("Tue Apr 26 11:14:45 2021")
# 1m
t10 = parser.parse("Tue Oct 08 06:00:20 2019") 
# 1y7m, 19m
t11 = parser.parse("Tue Jan 08 00:00:00 2019") 
# 2y4m, 28m


# create: date of object creation
# now: time now
# li: a list of string indicate time (in any language)
# lst: suffix (in any language)
# long: display length
def howLongAgo(create, now, li, lst, long=2):
    dif = create - now
    print(dif.days)
    sec = dif.days * 24 * 60 * 60 + dif.seconds
    minute = sec // 60
    sec %= 60
    hour = minute // 60
    minute %= 60
    day = hour // 24
    hour %= 24
    week = day // 7
    day %= 7
    month = (week * 7) // 30
    week %= 30
    year = month // 12
    month %= 12
    s = []
    for ii, tt in enumerate([sec, minute, hour, day, week, month, year]):
        ss = li[ii]
        if tt != 0:
            if tt == 1:
                s.append(str(tt) + ss)
            else:
                s.append(str(tt) + ss + 's')

    return ' '.join(list(reversed(s))[:long]) + ' ' + lst



t = howLongAgo(t1, t11, [
    'second', 
    'minute',
    'hour', 
    'day',
    'week', 
    'month',
    'year',
], 'ago')
print(t)
# 2years 4months ago

其他回答

Date和datetime对象(以及time)支持一种迷你语言来指定输出,并且有两种方式来访问它:

直接方法调用:dt。strftime(这里的格式) 格式化方法(python 2.6+): '{: Format here}'.format(dt) f-strings (python 3.6+): f'{dt:format here}'

所以你的例子可以是这样的:

dt。strftime('日期是%b %d, %Y') '日期为{:%b %d, %Y}'.format(dt) f'日期为{dt:%b %d, %Y}'

在这三种情况下,输出结果是:

日期是2012年2月23日

为了完整起见:你也可以直接访问对象的属性,但这样你只能得到数字:

'The date is %s/%s/%s' % (dt.month, dt.day, dt.year)
# The date is 02/23/2012

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


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

%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.

你可以用下面的方法将datetime转换为字符串:

from datetime import datetime

date_time = datetime(2012, 2, 23, 0, 0)
date = date_time.strftime('%m/%d/%Y')
print("date: %s" % date)

以下是一些可以用来将datetime转换为字符串的模式:

为了更好地理解,您可以参考这篇关于如何在Python或官方strftime文档中将字符串转换为datetime和datetime转换为字符串的文章

如果您正在寻找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'

但是注意下面的事情。如果其他解决方案会在变量为None时引发AttributeError,在这种情况下,您将收到一个'None'字符串。

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

类型特定的格式也可以使用:

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

输出:

'02/23/2012'

一种距离现在有多远的方法

通过传入参数li来支持不同的语言,这是一个对应的时间戳列表。

from datetime import datetime
from dateutil import parser

t1 = parser.parse("Tue May 26 15:14:45 2021")
t2 = parser.parse("Tue May 26 15:9:45 2021")
# 5min
t3 = parser.parse("Tue May 26 11:14:45 2021")
# 4h
t4 = parser.parse("Tue May 26 11:9:45 2021")
# 1day
t6 = parser.parse("Tue May 25 11:14:45 2021")
# 1day4h
t7 = parser.parse("Tue May 25 11:9:45 2021")
# 1day4h5min
t8 = parser.parse("Tue May 19 11:9:45 2021")
# 1w
t9 = parser.parse("Tue Apr 26 11:14:45 2021")
# 1m
t10 = parser.parse("Tue Oct 08 06:00:20 2019") 
# 1y7m, 19m
t11 = parser.parse("Tue Jan 08 00:00:00 2019") 
# 2y4m, 28m


# create: date of object creation
# now: time now
# li: a list of string indicate time (in any language)
# lst: suffix (in any language)
# long: display length
def howLongAgo(create, now, li, lst, long=2):
    dif = create - now
    print(dif.days)
    sec = dif.days * 24 * 60 * 60 + dif.seconds
    minute = sec // 60
    sec %= 60
    hour = minute // 60
    minute %= 60
    day = hour // 24
    hour %= 24
    week = day // 7
    day %= 7
    month = (week * 7) // 30
    week %= 30
    year = month // 12
    month %= 12
    s = []
    for ii, tt in enumerate([sec, minute, hour, day, week, month, year]):
        ss = li[ii]
        if tt != 0:
            if tt == 1:
                s.append(str(tt) + ss)
            else:
                s.append(str(tt) + ss + 's')

    return ' '.join(list(reversed(s))[:long]) + ' ' + lst



t = howLongAgo(t1, t11, [
    'second', 
    'minute',
    'hour', 
    'day',
    'week', 
    'month',
    'year',
], 'ago')
print(t)
# 2years 4months ago