1

i have a timestamp that looks like this 2015-11-06T14:20:14.011+01:00. I would like to parse it to datetime. I have the idea that i can use %Y-%m-%dT%H:%M:%S.%f%z as representation of this.

But the problem is the colon in the timezone. How can i remove the colon in the Timezone or is there a better way as the %z?

FrankStein
  • 85
  • 13

3 Answers3

2

You have an ISO 8601 datetime string. Don't bother parsing it or fiddling with it by hand (see: XY Problem). Use the iso8601 library for Python.

import iso8601
parsed = iso8601.parse_date("2015-11-06T14:20:14.011+01:00")

If you want to remove the timezone information from it, use the replace method.

tz_stripped = parsed.replace(tzinfo=None)
Community
  • 1
  • 1
Tom Morris
  • 3,979
  • 2
  • 25
  • 43
0
import re
original = '2015-11-06T14:20:14.011+01:00'
replaced = re.sub(r'([+-]\d+):(\d+)$', r'\1\2', original)
# replaced == '2015-11-06T14:20:14.011+0100'

This will replace the colon only when it is preceded by a plus or minus, and surrounded by digits until the end of the string.

Sebastian
  • 2,678
  • 25
  • 24
0

I think the best way to do this is with dateutils https://labix.org/python-dateutil

from dateutil.parser import parse
original = '2015-11-06T14:20:14.011+01:00'
print "Original Date {}".format(original)
new_date =  parse(original)
print new_date
print type(new_date)
# print new_date.hour
# print new_date.minute
# print new_date.second
print "New Date 1 {}".format(new_date.strftime('%Y-%m-%d %H:%M:%S'))
print "New Date 2 {}".format(new_date.strftime('%Y-%m-%dT%H:%M:%S.%f%z'))

Output:

Original Date 2015-11-06T14:20:14.011+01:00
2015-11-06 14:20:14.011000+01:00
<type 'datetime.datetime'>
New Date 1 2015-11-06 14:20:14
New Date 2 2015-11-06T14:20:14.011000+0100

Regards

nguaman
  • 925
  • 1
  • 9
  • 23