将Twitter XML日期转换为Python日期对象

时间:2012-12-11 21:51:00

标签: python xml date datetime twitter

我正在尝试将Twitter的“created_at”标记信息从XML文件转换为Python中的日期对象。我拼凑了一些代码,这些代码让我大部分时间都在那里,但是当我尝试将我找到的日期与其他日期对象进行比较时,它会崩溃。这是我到目前为止所做的:

import time
from datetime import datetime

#Twitter part removed... generates a list of dates from the XML called date_list

#Takes the first item from the list (date_list) and converts it to a string
date_str = str(date_list[0])

#Takes the string (date_str) and converts it to datetime
time_struct = time.strptime(date_str, "%a %b %d %H:%M:%S +0000 %Y")
date_datetime = datetime.fromtimestamp(time.mktime(time_struct))

#Converts datetime to just date
date = date_datetime.date()

if date_datetime < datetime.now():
    print "yes"

if date < datetime.date.today():
    print "yes, also"

就输出而言,我得到一个是,然后“AttributeError:'method_descriptor'对象在最后一行没有'今天'属性。”

我尝试将导入更改为“导入日期时间”,但后来我收到以下错误AttributeError: 'module' object has no attribute 'fromtimestamp'并且没有输出。

似乎我导入日期时间和代码的fromtimestamp部分停止工作或我导入“从datetime import datetime”,我无法创建日期对象?我已经看过其他线程可以帮助你从Twitter日期到日期时间,但是你如何获得最新的日期(没有分钟,秒等)?

1 个答案:

答案 0 :(得分:0)

请尝试datetime.now().date()datetime.today().date()。否则,您还需要from datetime import datedate.today()