Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert unicode to datetime proper strptime format

I am trying to convert a unicode object to a datetime object.

I read through the documentation: http://docs.python.org/2/library/time.html#time.strptime

and tried

datetime.strptime(date_posted, '%Y-%m-%dT%H:%M:%SZ') 

but I get the error message ValueError: time data '2014-01-15T01:35:30.314Z' does not match format '%Y-%m-%dT%H:%M:%SZ'

Any feedback on what is the proper format?

I appreciate the time and expertise.

like image 733
bbrooke Avatar asked Jan 16 '14 01:01

bbrooke


People also ask

What is Strptime ()?

The strptime() function in Python is used to format and return a string representation of date and time. It takes in the date, time, or both as an input, and parses it according to the directives given to it.

How do you use date Strptime?

It is also possible to get the string datetime in yyyy-mm-dd datetime format. yyyy-mm-dd stands for year-month-day. We can convert string format to DateTime by using the strptime() function. We will use the '%Y/%m/%d' format to get the string to datetime.


2 Answers

You can parse the microseconds:

from datetime import datetime
date_posted = '2014-01-15T01:35:30.314Z'
datetime.strptime(date_posted, '%Y-%m-%dT%H:%M:%S.%fZ')
like image 110
Velimir Mlaker Avatar answered Oct 03 '22 04:10

Velimir Mlaker


One option is to let dateutil do the job:

>>> from dateutil import parser
>>> parser.parse('2014-01-15T01:35:30.314Z')
datetime.datetime(2014, 1, 15, 1, 35, 30, 314000, tzinfo=tzutc())
like image 38
alecxe Avatar answered Oct 03 '22 04:10

alecxe