Populating a Django DateTimeField with feedparser
Asked Answered
N

2

5

I'm attempting to read my school's athletics/activities calendar, available in iCal or RSS format, into a Django Events model using feedparser.

Everything works, except the dates. Feedparser populates item.updated_parsed with a "9-tuple" but I can't figure out how to make this into something Django will accept in a DateTimeField. (I've used those before, but they've only ever been populated by datetime.datetime.now()).

Any ideas?

Nuthouse answered 9/6, 2011 at 1:57 Comment(0)
H
9

Covert the time.struct_time object into a datetime.datetime object:

from time import mktime
from datetime import datetime
dt = datetime.fromtimestamp(mktime(item['updated_parsed']))
Horologe answered 9/6, 2011 at 2:5 Comment(1)
This is fine. If you want to throw away the timezone info.Mabel
S
2

Well the Django DateTime field accepts python datetime.datetime objects so you have to convert from what Feedparser is providing you, and a datetime object. That's easy enough:

from datetime import datetime
time_object = datetime(nine_tuple[:8])

EDIT: How do you convert a Python time.struct_time object into a datetime object?

Specialist answered 9/6, 2011 at 2:6 Comment(1)
This straight-up doesn't work. datetime doesn't accept a tuple as input. You can do datetime(*item.updated_parsed[:7]), but, natch, that drops the timezone info again.Mabel

© 2022 - 2024 — McMap. All rights reserved.