4

Having a timestamp as string like 2016-09-22T13:57:31.2311892-04:00, how can one get the datetime object?

I've tried using strptime for this, but I got two issues:

  • I need to remove : from the timezone part, at the end, for %z to work properly.
  • The microseconds part has 7 digits, but strptime handles only up to 6 digits.

Is there a way to parse timestamps in this format without modifying* the string itself before passing to strptime?

* - by modifying, I think of removing the last microsecond digit, and removing the last :.

Note: This is for inserting a record in MySQL. If that helps.

Renato Oliveira
  • 456
  • 2
  • 7
  • 21
  • Possible duplicate of [Convert timestamps with offset to datetime obj using strptime](https://stackoverflow.com/questions/12281975/convert-timestamps-with-offset-to-datetime-obj-using-strptime) – pktangyue May 24 '18 at 03:45
  • @pktangyue this is not a duplicate question. I'm asking how to handle two different extra characters using the method, not how to make the conversion itself. – Renato Oliveira May 24 '18 at 03:48
  • In python2 `strptime` do not support 7 digits microseconds and `%z` for timezone. That means using a third lib will be a better way. – pktangyue May 24 '18 at 03:58
  • Using python 3 here. – Renato Oliveira May 24 '18 at 04:02
  • You said 'removing the last microsecond digit, and removing the last :'. This may be simple enough. – pktangyue May 24 '18 at 04:14

1 Answers1

2

How about convert like this:

dt = datetime.strptime(s[:-len('2-04:00')], '%Y-%m-%dT%H:%M:%S.%f')
# datetime.datetime(2016, 9, 22, 13, 57, 31, 231189)

https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

Suddenly found a useful method at django:

from django.utils.dateparse import parse_datetime
dt = parse_datetime('2016-09-22T13:57:31.2311892-04:00')
# datetime.datetime(2016, 9, 22, 13, 57, 31, 231189, tzinfo=<django.utils.timezone.FixedOffset object at 0x7f20184f8390>)

https://docs.djangoproject.com/en/2.0/ref/utils/#module-django.utils.dateparse

Another pythonic format (use maya https://github.com/kennethreitz/maya):

# pip install maya
import maya
maya.parse('2016-09-22T13:57:31.2311892-04:00').datetime()
# datetime.datetime(2016, 9, 22, 17, 57, 31, 231189, tzinfo=<UTC>)
Waket Zheng
  • 5,065
  • 2
  • 17
  • 30
  • So you are saying that basically I don't need the timezone info? Maybe I can store it in another column? Now that I think of it, it makes sense. This would allow a conversion on-the-fly, based on the user's timezone. Was that your thought? – Renato Oliveira May 24 '18 at 03:52
  • @RenatoOliveira I edit my answer and fix the timezone. – Waket Zheng May 24 '18 at 10:51