frazman
frazman

Reputation: 33293

How to convert string into datetime object in python?

I have date in following format

 d  = '2014-03-17 13:57:59-07:00'

How do I convert the above into timestamp object The following works

d1 = datetime.datetime.strptime(d, "%Y-%m-%d %H:%M:%S-07:00")

But then 7 is hardcoded.. i am not sure what that is? How do i ignore that part

Upvotes: 1

Views: 103

Answers (2)

user4322779
user4322779

Reputation:

Arrow has format directives for time zone offsets with and without a colon, functionality for converting to and from datetime objects and works with Python 2 and 3. Assuming that its been installed, which can be done with 'pip install arrow', here is how it can be used to convert '2014-03-17 13:57:59-07:00' to a datetime object:

import arrow
d = '2014-03-17 13:57:59-07:00'
f = 'YYYY-MM-DD H:mm:ssZ'
d1 = arrow.get(d, f).datetime

Documentation for arrow is at http://crsmithdev.com/arrow/.

Upvotes: 1

Simeon Visser
Simeon Visser

Reputation: 122506

You can use the dateutil package which supports parsing a string to a datetime. You can install it by doing:

pip install python-dateutil

And then:

import dateutil.parser

d = dateutil.parser.parse('2014-03-17 13:57:59-07:00')

The 7 or 8 in your dates is the offset from UTC - it is used to indicate in what timezone the datetime is located.

Upvotes: 4

Related Questions