Just convert it to timestamp
datetime.datetime.fromtimestamp(ms/1000.0)
Answer from vartec on Stack Overflowpython - How to convert milliseconds to date and time format? - Stack Overflow
Convert python datetime to timestamp in milliseconds - Stack Overflow
How to convert a number of milliseconds since Year 0 into a pandas Timestamp (or some other object with year, month, day, hour, minute, second)?
python - Converting epoch time with milliseconds to datetime - Stack Overflow
Videos
To convert unix timestamp to datetime, you can use datetime.fromtimestamp(). The only problem, that your timestamp is in miliseconds, but function expect timestamp in seconds. To cut miliseconds you can divide timestamp to 1000.
Code:
from datetime import datetime
a = 1557975599999
date = datetime.fromtimestamp(a // 1000)
print(date)
Output:
2019-05-16 05:59:59
Upd.
@Daniel in comments noticed that fromtimestamp() accept floats, so we can save miliseconds from original timestamp. All we need is just to remove one symbol :D
date = datetime.fromtimestamp(a / 1000)
With Pandas’ to_datetime()
import pandas as pd
pd.to_datetime(a, unit='ms')
# Or with a dataframe(column):
df['date'] = pd.to_datetime(df['Millisecond_time'], unit='ms')
In Python 3 this can be done in 2 steps:
- Convert timestring to
datetimeobject - Multiply the timestamp of the
datetimeobject by 1000 to convert it to milliseconds.
For example like this:
from datetime import datetime
dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
'%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000
print(millisec)
Output:
1482223122760.0
strptime accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime object. The format string (second argument) specifies the actual format of the string that you have passed.
Here is the explanation of the format specifiers from the official documentation:
%d- Day of the month as a zero-padded decimal number.%m- Month as a zero-padded decimal number.%Y- Year with century as a decimal number%H- Hour (24-hour clock) as a zero-padded decimal number.%M- Minute as a zero-padded decimal number.%S- Second as a zero-padded decimal number.%f- Microsecond as a decimal number, zero-padded to 6 digits.
For those who search for an answer without parsing and losing milliseconds,
given dt_obj is a datetime:
python3 only, elegant
int(dt_obj.timestamp() * 1000)
both python2 and python3 compatible:
import time
int(time.mktime(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000)
How to convert a number of milliseconds since Year 0 (from a CDF) into a pandas Timestamp (or some other object with year, month, day, hour, minute, second)?
I think I can get it to work, but the way I'm doing it is extremely convoluted, and i feel like there has to be a simpler way.
Edit: in case anyone happens to have the same problem as me, which is: converting an epoch from cdflib into a date and time, where it starts out as a number of milliseconds since year 0, all you have to do is:
import cdflib
cdf_file = cdflib.CDF("filename")
epoch = cdf_file.varget("Epoch")
time_array = cdflib.epochs.CDFepoch.to_datetime(epoch) This gives you information on the date and time for each point.
Here is the documentation:
https://cdflib.readthedocs.io/en/latest/api/cdflib.epochs.CDFepoch.html#cdflib.epochs.CDFepoch
Use datetime.datetime.fromtimestamp:
>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'
%f directive is only supported by datetime.datetime.strftime, not by time.strftime.
UPDATE Alternative using %, str.format:
>>> import time
>>> s, ms = divmod(1236472051807, 1000) # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
those are miliseconds, just divide them by 1000, since gmtime expects seconds ...
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))
The reason for this is that date_to_mil works with UTC and mil_to_date doesn't. You should replace utcfromtimestamp with fromtimestamp.
Further explanation:
In your code, epoch is the date of the epoch in UTC (but the object is without any time-zone). But date is local since fromtimestamp returns a local time:
If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive
So you subtract the UTC epoch from the local datetime and you get a delay which is your local delay to UTC.
If input is UTC then to get POSIX timestamp as integer milliseconds:
from datetime import datetime, timedelta
def timestamp_millis(utc_time, epoch=datetime(1970, 1, 1)):
"""Return milliseconds since Epoch as integer."""
td = utc_time - epoch
return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) // 10**3
Note: the formula may produce a different result from: int(td.total_seconds() * 1000).
And in reverse: to get UTC time from POSIX time given as milliseconds:
def datetime_from_millis(millis, epoch=datetime(1970, 1, 1)):
"""Return UTC time that corresponds to milliseconds since Epoch."""
return epoch + timedelta(milliseconds=millis)
It supports both positive and negative millis.
Note: None handling happens outside these functions.
Example:
>>> datetime_from_millis(1394462888000)
datetime.datetime(2014, 3, 10, 14, 48, 8)
>>> datetime.utcfromtimestamp(1394462888)
datetime.datetime(2014, 3, 10, 14, 48, 8)
>>> timestamp_millis(_)
1394462888000
The result is different from the one in your question!
gmtime(0).year != 1970 and TZ=right/UTC cases are ignored.