ehertele
ehertele

Reputation: 221

split timestamp by hour

I have a list of timestamps in ISO format

[u"2000-01-01T00:00:00+00:00", u"2000-01-01T00:00:00+00:00", ... ]

I'm trying to split each string by the hour. However, using "string".strp(":") obviously won't work, because of a too many values to unpack error (due to several :'s) and "string".strp(":%S") gives a value error of more than one value to unpack. Any ideas?

Upvotes: 2

Views: 1094

Answers (2)

Julian
Julian

Reputation: 3429

You have two choices. You can either use datetime.datetime.strptime to give you datetime objects, and then just do dt.hour, which you may want to do anyways, depending on what you're doing with these.

Or, alternatively, if you want to just use string processing as you are, you can use str.split as you've shown, but with its optional second argument, which is the maximum number of times to split, so s.split(":", 1). Or similarly, str.partition, which basically would do the same as that but not raise an error for a thing without a ":". With both of these, you'd need to then strip off the things at the beginning of the time using slicing.

Upvotes: 2

Hans Z
Hans Z

Reputation: 4744

iso8601 is a wonderful, open source python module to parse ISO datetime strings http://code.google.com/p/pyiso8601/

It turns it into python's native datetime type which should be easier to work with.

Upvotes: 2

Related Questions