I’m trying to convert Twitter’s “created_at” tag information from an XML file to a date object in Python. I pieced together some code that gets me most of the way there, but then breaks down when I try to compare the date I found with other date objects. Here’s what I have so far:
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"
As far as output, I get one yes and then an “AttributeError: ‘method_descriptor’ object has no attribute ‘today'” for the last line.
I tried changing the import to just “import datetime”, but then I get the following error AttributeError: 'module' object has no attribute 'fromtimestamp' and no output.
It seems like either I import datetime and the fromtimestamp part of the code stops working or I import “from datetime import datetime” and I can’t created date objects? I’ve seen other threads that help you get from the Twitter date to datetime, but how do you get all the way to date (no minutes, seconds, etc)?
Try
datetime.now().date()ordatetime.today().date()instead. Otherwise, you also need tofrom datetime import dateto dodate.today()