在python中将datetime64数据转换为datetime

问题描述 投票:0回答:2

我下载了一个包含 datetime64 类型时间数据的数据集,我需要它的格式,其中每个日期值分为年、月和日作为不同的元素。我怎样才能做到这一点?

作为参考,这是一个元素,我需要类似 (2010, 1, 1) 的东西,小时,分钟等并不重要:

tiempo[0]
Out[207]: numpy.datetime64('2010-01-01T12:00:00.000000000')

我尝试将其转换为时间戳,然后转换为日期时间,但我无法使其工作。

ts = (tiempo - np.datetime64('1970-01-01T00:00:00Z'))// np.timedelta64(1, 's')
python datetime-format
2个回答
0
投票

这样的事情怎么样:

import numpy as np

tiempo = np.datetime64('2010-01-01T12:00:00.000000000')

year = tiempo.astype('datetime64[Y]').astype(int) + 1970
month = tiempo.astype('datetime64[M]').astype(int) % 12 + 1
day = tiempo.astype('datetime64[D]').astype(int) % (365 // 12) + 1

print(year, month, day)

0
投票

一种方法:

from dateutil.parser import parse

def to_date(dt):
    return parse(str(dt)).date()

然后将此函数应用于数据集的所有元素。 假设 tiempo 是 pandas 系列,你可以得到这样的日期:

dates = tiempo.apply(to_date)

如果您期望输入中没有任何内容(即数据库中存在 NULL),最好这样做:

dates = tiempo.apply(lambda x: pd.NaT if x is None else to_date(x))
© www.soinside.com 2019 - 2024. All rights reserved.