1

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

7
  • @PadraicCunningham.. but in my data.. sometimes it is 7 and sometimes it is 8 or somethng else.. how do i parse it Commented Sep 6, 2015 at 18:31
  • 2
    Simplest way is to install and use dateutil.parser.parse(d) Commented Sep 6, 2015 at 18:32
  • You can also calculate it yourself by slicing Commented Sep 6, 2015 at 18:37
  • %z is the utc offset code, see strftime.org and try d1 = datetime.datetime.strptime(d, "%Y-%m-%d %H:%M:%S%z") Commented Sep 6, 2015 at 18:38
  • 1
    @PadraicCunningham: thank you for pointing that out. With Python 3, time.strftime's %z directive unfortunately does not support colon in time zone offset. The colon could be removed with re.sub for a Python 3 solution and arrow suppports time zone offsets with and without a colon for Python 2 and 3. Commented Sep 6, 2015 at 21:34

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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/.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.