Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

python - Converting an array datatime.datetime to float

Is it possible to convert something like this;

array([datetime.datetime(2014, 2, 1, 0, 0, 0, 100000),
       datetime.datetime(2014, 2, 1, 0, 0, 0, 300000),
       datetime.datetime(2014, 2, 1, 0, 0, 0, 500000), ...,
       datetime.datetime(2014, 2, 1, 19, 30, 0, 500000),
       datetime.datetime(2014, 2, 1, 19, 30, 0, 700000),
       datetime.datetime(2014, 2, 1, 19, 30, 0, 900000)], dtype=object)

to this:

array([  1.39277301e+09,   1.39277301e+09,   1.39277301e+09, ...,
         1.39285442e+09,   1.39285442e+09,   1.39285442e+09])

I would basically like to convert the datetime.datetime into a timestamp, with dtype = float.

question from:https://stackoverflow.com/questions/65933913/convert-date-to-float-in-numpy

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The best way to get a timestamp is by subtracting epoch from your datetime as:

Code:

import datetime as dt

times = np.array([
    dt.datetime(2014, 2, 1, 0, 0, 0, 100000),
    dt.datetime(2014, 2, 1, 0, 0, 0, 300000),
    dt.datetime(2014, 2, 1, 0, 0, 0, 500000),
])

# get a datetime that is equal to epoch
epoch = dt.datetime(1970, 1, 1)

for t in [(d - epoch).total_seconds() for d in times]:
    print('%.6f' % t)

Results:

1391212800.100000
1391212800.300000
1391212800.500000

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...