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

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

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


当前回答

我已经使用此方法将日期插入JSON对象

my_json_string = json.dumps({'date_of_birth': '''{}'''.format(date_of_birth)})

其他回答

另一个选择:

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

到目前为止最性感的版本是格式字符串。

from datetime import datetime

print(f'{datetime.today():%Y-%m-%d}')

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

通过传入参数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

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

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

你可以用下面的方法将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转换为字符串的文章