Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting utc time string to datetime object

I'm using the Paypal API and I get back a timestamp in the following format. I try to parse this to a datetime object using strptime, but I get the following error:

(Pdb) datetime.strptime('2012-03-01T10:00:00Z','%Y-%M-%dT%H:%M:%SZ') *** error: redefinition of group name 'M' as group 5; was group 2 

Also, as this format is supposed to be quite a standard format isn't there a function available for this?

EDIT:

Ok seems to be a typo. First %M should be %m

like image 582
arno_v Avatar asked Feb 24 '12 15:02

arno_v


People also ask

How do you convert UTC time to local time?

Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.).

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

How do you convert UTC to time in python?

Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime. Finally, use datetime. astimezone() method to convert the datetime to UTC.


1 Answers

The parser from dateutil is your friend.

You'll have to pip install dateutil but you've save bags and bags of date conversion code:

pip install python-dateutil 

You can use it like this.

from dateutil import parser ds = '2012-03-01T10:00:00Z' # or any date sting of differing formats. date = parser.parse(ds) 

You'll find you can deal with almost any date string formats with this parser and you'll get a nice standard python date back

like image 78
Matt Alcock Avatar answered Sep 22 '22 22:09

Matt Alcock