5

how I have a simple question. I need to convert a date in string format to a number:

time = '2014-03-05 07:22:26.976637+00:00'
type(time)
      str

I would like to convert this date to a unique number

Thank you.

emax
  • 6,965
  • 19
  • 74
  • 141
  • 2
    This question already has an answer: http://stackoverflow.com/questions/466345/converting-string-into-datetime – romeric Sep 22 '15 at 21:54
  • possible duplicate of [python: convert date timestamp to epoch unix time and figure out number of days remaining?](http://stackoverflow.com/questions/26132745/python-convert-date-timestamp-to-epoch-unix-time-and-figure-out-number-of-days) – Chad S. Sep 22 '15 at 22:00
  • Thank you very much to your answers, however I don't know which format use to convert my string to a date with strptime. I am doing ` dt = datetime.strptime(time, '%m/%d/%Y %I:%M:%S.%f')` but it does not work – emax Sep 22 '15 at 22:02

2 Answers2

7

In Python 3.7+:

>>> from datetime import datetime
>>> datetime.fromisoformat('2014-03-05 07:22:26.976637+00:00').timestamp()
1394004146.976637

There are two steps:

Convert input rfc-3339 time string into datetime object

#!/usr/bin/env python
from datetime import datetime

time_str = '2014-03-05 07:22:26.976637+00:00'
utc_time = datetime.strptime(time_str[:26], '%Y-%m-%d %H:%M:%S.%f')
assert time_str[-6:] == '+00:00'

Find number of the microseconds since Epoch for given datetime

from datetime import datetime, timedelta

epoch = datetime(1970, 1, 1)

def timestamp_microsecond(utc_time):
    td = utc_time - epoch
    assert td.resolution == timedelta(microseconds=1)
    return (td.days * 86400 + td.seconds) * 10**6 + td.microseconds

print(timestamp_microsecond(utc_time))
# -> 1394004146976637

The advantage is that you could convert this unique number back to the corresponding UTC time:

utc_time = epoch + timedelta(microseconds=1394004146976637)
# -> datetime.datetime(2014, 3, 5, 7, 22, 26, 976637)

Follow the links if you need to support arbitrary utc offsets (not just UTC time).

If you need to accept a leap second as the input time; see Python - Datetime not accounting for leap second properly?

jfs
  • 399,953
  • 195
  • 994
  • 1,670
1

I would like to convert this date to a unique number

The standard unix thing to do would be to convert to seconds since epoch. However, if you just want a unique number:

>>> time = '2014-03-05 07:22:26.976637+00:00'
>>> int(''.join(c for c in time if c.isdigit()))
201403050722269766370000L

If, instead of a unique number, you want a python datetime object, then use:

>>> from dateutil import parser
>>> dt = parser.parse(time)
>>> dt
datetime.datetime(2014, 3, 5, 7, 22, 26, 976637, tzinfo=tzutc())
John1024
  • 109,961
  • 14
  • 137
  • 171