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

frazman
  • 32,081
  • 75
  • 184
  • 269
  • @PadraicCunningham.. but in my data.. sometimes it is 7 and sometimes it is 8 or somethng else.. how do i parse it – frazman Sep 06 '15 at 18:31
  • 2
    Simplest way is to install and use `dateutil.parser.parse(d)` – Padraic Cunningham Sep 06 '15 at 18:32
  • You can also calculate it yourself by slicing – Padraic Cunningham Sep 06 '15 at 18:37
  • %z is the utc offset code, see http://strftime.org/ and try d1 = datetime.datetime.strptime(d, "%Y-%m-%d %H:%M:%S%z") –  Sep 06 '15 at 18:38
  • @TrisNefzger, that is not going to work, the format is not correct, %z also only works for python3.2+ – Padraic Cunningham Sep 06 '15 at 18:39
  • This answer shows how to slice http://stackoverflow.com/a/23122493/2141635 – Padraic Cunningham Sep 06 '15 at 18:40
  • 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. –  Sep 06 '15 at 21:34

2 Answers2

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.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
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/.