如何在Python中以毫秒为单位创建日期时间?

问题:如何在Python中以毫秒为单位创建日期时间?

我可以通过java.util.Date(milliseconds)在Java 创建类似的Date对象。如何在Python中创建可比对象?

分配一个Date对象,并将其初始化为表示自标准基准时间(即epoch)以来的指定毫秒数,即标准时间1970年1月1日,格林尼治标准时间00:00:00。

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

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.


回答 0

只需将其转换为时间戳

datetime.datetime.fromtimestamp(ms/1000.0)

Just convert it to timestamp

datetime.datetime.fromtimestamp(ms/1000.0)

回答 1

那这个呢?我认为可以指望它处理1970年之前和2038年之后的日期。

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

如Python标准库中所述:

如果时间戳超出平台C localtime()或gmtime()函数支持的值范围,则fromtimestamp()可能会引发ValueError。通常将此限制在1970年到2038年之间。

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

target_date_time_ms = 200000 # or whatever
base_datetime = datetime.datetime( 1970, 1, 1 )
delta = datetime.timedelta( 0, 0, 0, target_date_time_ms )
target_date = 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.


回答 2

由于使用了熊猫而有点沉重,但可以:

import pandas as pd
pd.to_datetime(msec_from_java, unit='ms').to_pydatetime()

Bit heavy because of using pandas but works:

import pandas as pd
pd.to_datetime(msec_from_java, unit='ms').to_pydatetime()

回答 3

import pandas as pd

Date_Time = pd.to_datetime(df.NameOfColumn, unit='ms')
import pandas as pd

Date_Time = pd.to_datetime(df.NameOfColumn, unit='ms')