# Numpy库基础分析——详解datetime类型的处理

2019.05.20 22:39 793浏览

``````#时间字符串转numpy.datetime64
datetime_nd=np.datetime64('2019-01-01')
print(type(datetime_nd))#<class 'numpy.datetime64'>
``````

``````#numpy.datetime64转时间字符串
datetime_str=np.datetime_as_string(datetime_nd)
print(type(datetime_str))#<class 'numpy.str_'>
``````

``````datetime_array = np.array(['2019-01-05','2019-01-02','2019-01-03'], dtype='datetime64')
print(datetime_array)#['2019-01-05' '2019-01-02' '2019-01-03']
print(type(datetime_array))#<class 'numpy.ndarray'>
print(type(datetime_array[0]))#<class 'numpy.datetime64'>
``````

``````datetime_array = np.arange('2019-01-05','2019-01-10', dtype='datetime64')
print(datetime_array)#['2019-01-05' '2019-01-06' '2019-01-07' '2019-01-08' '2019-01-09']
``````

``````# generate year datetime array
datetime_array = np.arange('2018-01-01','2020-01-01', dtype='datetime64[Y]')
print(datetime_array)#['2018' '2019']

# generate month datetime array
datetime_array = np.arange('2019-01-01','2019-10-01', dtype='datetime64[M]')
print(datetime_array)#['2019-01' '2019-02' '2019-03' '2019-04' '2019-05' '2019-06' '2019-07' '2019-08' '2019-09']

# generate week datetime array
datetime_array = np.arange('2019-01-05','2019-02-10', dtype='datetime64[W]')
print(datetime_array)#['2019-01-03' '2019-01-10' '2019-01-17' '2019-01-24' '2019-01-31']

# generate ms datetime array
datetime_array = np.arange('2019-01-05','2019-01-10', dtype='datetime64[ms]')
print(datetime_array)
#['2019-01-05T00:00:00.000' '2019-01-05T00:00:00.001'
# '2019-01-05T00:00:00.002' ... '2019-01-09T23:59:59.997'
# '2019-01-09T23:59:59.998' '2019-01-09T23:59:59.999']
``````

``````#numpy.datetime64转化为datetime格式
datetime_df=datetime_nd.astype(datetime.datetime)
print(type(datetime_df))#<class 'datetime.date'>
``````

``````# numpy.datetime64 calculations
datetime_delta = np.datetime64('2009-01-01') - np.datetime64('2008-01-01')
print(datetime_delta)#366 days
print(type(datetime_delta))#<class 'numpy.timedelta64'>

datetime_delta = np.datetime64('2009') + np.timedelta64(20, 'D')
print(datetime_delta)#2009-01-21

datetime_delta = np.datetime64('2011-06-15T00:00') + np.timedelta64(12, 'h')
print(datetime_delta)#2011-06-15T12:00

datetime_delta = np.timedelta64(1,'W') / np.timedelta64(1,'D')
print(datetime_delta)#7.0
``````

0人点赞

• 推荐
• 评论
• 收藏
• 共同学习，写下你的评论

0/150