I am receiving twitter messages that are sent at a certain date in the following format from twitter:
Tue Mar 29 08:11:25 +0000 2011
I want to store these dates in 'timestamp with time zone' field in postgresql with djangos DateTimeField field. When I store that string however I get this error:
ValidationError: [u'Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format.']
can I automatically transform the twitter datetype to a python datetime time (that does work elsewhere in my app for saving dates).
Give this a go. It assumes the date format from twitter is RFC822 compliant (see the question linked to by @Adrien).
A naive datetime object is constructed (i.e. no timezone info). It is adjusted according to the timezone offset to UTC. Unless you have a need to keep the original timezone, I'd store the date time as UTC and format to local time when you display it.
Using a similar strategy as SoFolichon proposed, in Python 3.x you can also use
pytz
like:Writing something like this should convert a twitter date to a timestamp.
How about this? It doesn't need any formatting strings.
My system is at GMT +2 hence the difference included.
The following code will print a nice date (local time) from a Twitter date (UTC).
you can convert the date using
datetime.strptime()
, ortime.strptime()
. however, those two functions cannot parse the timezone offset (see this bug).so, the only solution i see is to split the date yourself, remove the timezone offset, feed the rest to
strptime()
, and process the offset manually...have a look at this question, where you will find some hints on how to parse the offset yourself.