如何在Python中从毫秒开始创建datetime?

2024-04-29 02:45:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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.


Tags: andtheto对象dateobjectutilit
3条回答

把它转换成时间戳

datetime.datetime.fromtimestamp(ms/1000.0)

有点重,因为使用熊猫,但工作:

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

这个怎么样?我想它可以用来处理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标准库中所述:

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.

相关问题 更多 >