在Pandas中将十进制数转换为日期时间

jucafojl  于 2023-03-16  发布在  其他
关注(0)|答案(3)|浏览(144)

我正在尝试将十进制数转换为datatime。dateframe示例如下:

timestep_time  vehicle_angle  vehicle_id  vehicle_pos  vehicle_speed  vehicle_x  vehicle_y  Cluster
0             0.00         113.79           0         5.10           0.00     295.36     438.47        1
1             1.00         113.79           0         6.73           1.63     296.85     437.82        1
2             1.01         203.94           1         5.10           0.00     278.32     434.32        9
3             2.00         113.79           0        10.00           3.27     299.84     436.50        1
4             2.01         203.94           1         6.50           1.40     277.75     433.04        9
5             2.02          23.94           2         5.10           0.00     255.88     375.91        1

我并不特别关心时间的实际单位,我只是需要它作为一个datetime对象。所以,我尝试了:

posBirch["timestep_time"] = pd.to_datetime(posBirch["timestep_time"], format='%M.%S')

and

posBirch["timestep_time"] = pd.to_datetime(posBirch["timestep_time"], format='%S.%f')

# Error:

ValueError: time data '0' does not match format '%M.%S' (match)

posBirch["timestep_time"] = pd.to_datetime(posBirch["timestep_time"], format='%S')

# Yields no error but drops decimal which I need to keep timesteps unique which I will later use for indexing i.e.:

1   1900-01-01 00:00:01         113.79           0         6.73           1.63     296.85     437.82        1
2   1900-01-01 00:00:01         203.94           1         5.10           0.00     278.32     434.32        9

posBirch["timestep_time"] = pd.to_datetime(posBirch["timestep_time"], format='%-S')

# Error:

ValueError: '-' is a bad directive in format '%-S'

我怎样才能把这个十进制数转换成一个唯一的日期时间值呢?单位并不重要,因为这是一个伪时间步长,但我想最好是秒。

b4lqfgs4

b4lqfgs41#

这将基于当前列“timestep_time”添加一个新列“Timestamp”。

def create_timestamp(val):
    mins = int(val)
    secs = int((val-mins) *60)
    return pd.Timestamp(year=2020, month=1, day=1, minute=mins, second=secs)
df['TimeStamp'] = create_timestamp(df['timestep_time'][0])
pieyvz9o

pieyvz9o2#

以下是最后奏效的方法:

posBirch['TimeStamp'] = pd.to_datetime(posBirch['timestep_time'], unit='s')
bakd9h0s

bakd9h0s3#

我从AWS响应中收到了一个Decimal纪元时间(毫秒)。我没有看到一个简单的方法来用Panda将其转换为datetime,除非你先将其转换为int或string。
我用了这个:

# cast from Decimal to int
df["creationDate"] = df["creationDate"].astype(int)

# convert Epoch with milliseconds to MONTH-YEAR
df["creationDate"] = pd.to_datetime(df["creationDate"], unit='ms').dt.strftime('%m-%Y')

我想要的输出是:

相关问题