Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a timestamp string with 7 digits on the microseconds part using strptime?

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.

like image 294
Renato Oliveira Avatar asked Oct 21 '25 11:10

Renato Oliveira


1 Answers

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>)
like image 131
Waket Zheng Avatar answered Oct 23 '25 23:10

Waket Zheng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!