196

How do I create a datetime in Python from milliseconds? I can create a similar Date object in Java by java.util.Date(milliseconds).

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Mateen Ulhaq
  • 21,459
  • 16
  • 82
  • 123
Joshua
  • 25,484
  • 22
  • 75
  • 106
  • related since seconds to milliseconds is just a factor: [Converting unix timestamp string to readable date](https://stackoverflow.com/q/3682748/10197418) – FObersteiner Sep 20 '21 at 08:32

5 Answers5

317

Just convert it to timestamp

datetime.datetime.fromtimestamp(ms/1000.0)
vartec
  • 125,354
  • 36
  • 211
  • 241
  • 28
    A note -- in Python 3, (/) will perform floating-point division. To perform integral division, use (//). – John Millikin Apr 14 '09 at 17:37
  • 5
    Don't you actually want float division anyway? Otherwise you're losing any precision below 1 second (held in the fractional part of the timestamp). Better to use ms/1000.0 with no truncation. – Brian Apr 14 '09 at 19:45
  • Not all platforms support fractional timestamps -- better to stick with POSIX's integers. – John Millikin Apr 14 '09 at 20:28
  • 4
    Surely datetime always supports it though? If we've got sub-second precision, it seems wrong to throw it away. If we don't there's no harm done - we just retain that original precision. – Brian Apr 14 '09 at 21:00
  • 48
    To keep the precision without using floats, you can also do: `datetime.utcfromtimestamp(ms//1000).replace(microsecond=ms%1000*1000)` – tsg Nov 09 '12 at 22:43
  • 2
    another problem with this solution: "fromtimestamp() may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. It’s common for this to be restricted to years in 1970 through 2038." - how long is your code expected to last??? – mike rodent Jul 25 '15 at 09:53
  • It gives local time. How can I get gmt – Yajana Rao Sep 20 '18 at 13:13
  • WHY it gives an exception in the years before 1970? Aren't those years as well – canbax Apr 17 '20 at 11:44
17

What about this? I presume it can be counted on to handle dates before 1970 and after 2038.

target_datetime_ms = 200000 # or whatever
base_datetime = datetime.datetime(1970, 1, 1)
delta = datetime.timedelta(0, 0, 0, target_datetime_ms)
target_datetime = base_datetime + delta

as mentioned in the Python standard lib:

fromtimestamp() may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. It’s common for this to be restricted to years in 1970 through 2038.

Very obviously, this can be done in one line:

target_dt = datetime(1970, 1, 1) + timedelta(milliseconds=target_dt_ms)
mike rodent
  • 12,285
  • 11
  • 88
  • 123
  • 9
    you could use `utc_time = datetime(1970, 1, 1) + timedelta(milliseconds=millis)` – jfs Jul 26 '15 at 01:55
14

Converting millis to datetime (UTC):

import datetime
time_in_millis = 1596542285000
dt = datetime.datetime.fromtimestamp(time_in_millis / 1000.0, tz=datetime.timezone.utc)

Converting datetime to string following the RFC3339 standard (used by Open API specification):

from rfc3339 import rfc3339
converted_to_str = rfc3339(dt, utc=True, use_system_timezone=False)
# 2020-08-04T11:58:05Z
Community
  • 1
  • 1
cahen
  • 13,856
  • 12
  • 44
  • 73
  • 1
    would be my accepted answer since Java's Date also refers to UTC by default (vs. Python's naive datetime / tz not set refers to *local time*). – FObersteiner Sep 20 '21 at 08:45
12

Bit heavy because of using pandas but works:

import pandas as pd
pd.to_datetime(msec_from_java, unit='ms').to_pydatetime()
mde
  • 294
  • 3
  • 8
11
import pandas as pd

Date_Time = pd.to_datetime(df.NameOfColumn, unit='ms')
Artem Krylov
  • 111
  • 1
  • 3