如何将 datetime.datetime 个对象的列表转换为 Python 中的日期?

How to convert a list of datetime.datetime objects to date in Python?

我正在使用名为 'pythonwhois' 的 Python whois API 并尝试提取 'creation_date' 以获得域名列表。我使用的代码是:

f = open (file,'r')
with open (output,'wt') as m:
    for line in f:
        line = line.strip('\n')
        domain = line.split(';')
        try:
            w = pythonwhois.get_whois(domain)
            c_date = (w['creation_date'])
            print (domain,c_date)

        except:
            pass

结果是 datetime.datetime 个对象的列表,如下所示:

domain,creation_date
('hostzi.com', [datetime.datetime(2009, 5, 12, 13, 4, 12)])
('daduru.com',  [datetime.datetime(2007, 4, 16, 10, 59)])
('callforest.com', [datetime.datetime(2006, 4, 23, 14, 29, 1)])

我想将 'creation_date' 列转换为 python 日期的字符串表示形式,格式为 Y/m/d。 有人可以帮忙吗?

您可以使用 strftime :

Return a string representing the date and time, controlled by an explicit format string:

>>> l=('hostzi.com', [datetime.datetime(2009, 5, 12, 13, 4, 12)])
>>> l[1][0].strftime('%Y/%m/%d')
'2009/05/12'

您也可以直接在主代码上执行此操作:

f = open (file,'r')
with open (output,'wt') as m:
    for line in f:
        line = line.strip('\n')
        domain = line.split(';')
        try:
            w = pythonwhois.get_whois(domain)
            c_date = (w['creation_date'])
            print (domain,c_date[0].strftime('%Y/%m/%d'))

        except:
            pass

要将 datetime.datetime 个对象转换为 datetime.date 个对象: https://docs.python.org/2/library/datetime.html#datetime.datetime.date

编辑: 将 datetime.datetime 个对象转换为 Y\m\d:

格式的字符串
d = datetime.datetime.now()
d.strftime("%Y\%m\%d")

https://docs.python.org/2/library/datetime.html#datetime.datetime.strftime