25

What is a classy way to store date and time information in a float in python with millisecond precision? Edit: I'm using python 2.7

I've hacked together the following:

DT = datetime.datetime(2016,01,30,15,16,19,234000) #trailing zeros are required
DN = (DT - datetime.datetime(2000,1,1)).total_seconds()
print repr(DN)

Output:

507482179.234

And then to revert back to datetime:

DT2 = datetime.datetime(2000,1,1) + datetime.timedelta(0, DN)
print DT2

Output:

2016-01-30 15:16:19.234000

But I'm really looking for something a little more classy and robust.

In matlab I would use the datenum and datetime functions:

DN = datenum(datetime(2016,01,30,15,16,19.234))

And to revert back:

DT = datetime(DN,'ConvertFrom','datenum')
Swier
  • 4,047
  • 3
  • 28
  • 52
  • Thanks J.F. Sebastian, you're right, I missed that question as I wasn't aware it was called a timestamp. I'll look into the other question and answer. – Swier Feb 15 '16 at 09:40

2 Answers2

36

Python 2:

def datetime_to_float(d):
    epoch = datetime.datetime.utcfromtimestamp(0)
    total_seconds =  (d - epoch).total_seconds()
    # total_seconds will be in decimals (millisecond precision)
    return total_seconds

def float_to_datetime(fl):
    return datetime.datetime.fromtimestamp(fl)

Python 3:

def datetime_to_float(d):
    return d.timestamp()

The python 3 version of float_to_datetime will be no different from the python 2 version above.

mit
  • 11,083
  • 11
  • 50
  • 74
jatinderjit
  • 1,359
  • 8
  • 21
  • 1
    your Python 2/3 `datetime_to_float()` versions are inconsistent unless your local timezone is UTC. – jfs Feb 13 '16 at 16:28
  • datetime.datetime.fromtimestamp() can also be used to avoid timezone conflict – Dai Jan 24 '18 at 13:34
15

In Python 3 you can use: timestamp (and fromtimestamp for the inverse).

Example:

>>> from datetime import datetime
>>> now = datetime.now()
>>> now.timestamp()
1455188621.063099
>>> ts = now.timestamp()
>>> datetime.fromtimestamp(ts)
datetime.datetime(2016, 2, 11, 11, 3, 41, 63098)
Stefan
  • 919
  • 2
  • 13
  • 24
second
  • 28,029
  • 7
  • 75
  • 76
  • ``datetime.datetime`` seems to have no ``timestamp`` attribute, is this for python 3? I'm using 2.7 (and forgot to mention, sorry) Edit: from jatinderjit's answer it seems .timestamp is indeed python 3 only – Swier Feb 11 '16 at 11:34