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:
: from the timezone part, at the end, for %z to work properly.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.
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
mayahttps://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>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With