Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python datetime to float with millisecond precision [duplicate]

Tags:

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')
like image 918
Swier Avatar asked Feb 11 '16 10:02

Swier


People also ask

How do I convert time to milliseconds Python?

A simple solution is to get the timedelta object by finding the difference of the given datetime with Epoch time, i.e., midnight 1 January 1970. To obtain time in milliseconds, you can use the timedelta. total_seconds() * 1000 .

How do I show milliseconds in Python?

%% – A literal '%' character. To use this function to produce milliseconds in python %f is used in format code.

How do I convert datetime to seconds in Python?

To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.


1 Answers

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.

like image 189
jatinderjit Avatar answered Oct 25 '22 08:10

jatinderjit