0

I'm trying to figure out the easiest way to automate the conversion of an array of seconds into datetime. I'm very familiar with converting the seconds from 1970 into datetime, but the values that I have here are for the seconds elapsed in a given day. For example, 14084 is the number if seconds that has passed on 2011,11,11, and I was able to generate the datetime below.

str(dt.timedelta(seconds = 14084))
Out[245]: '3:54:44'

dt.datetime.combine(date(2011,11,11),time(3,54,44))
Out[250]: datetime.datetime(2011, 11, 11, 3, 54, 44)

Is there a faster way of conversion for an array.

3
  • take a look at pandas.to_datetime and pandas.to_timedelta Commented Sep 2, 2020 at 22:57
  • Why don't you just do datetime(2011,11,11) + timedelta(seconds=14084)? Commented Sep 2, 2020 at 22:59
  • @Selcuk I'll try that out. Thanks Commented Sep 2, 2020 at 23:03

2 Answers 2

1

numpy has support for arrays of datetimes with a timedelta type for manipulating them: https://numpy.org/doc/stable/reference/arrays.datetime.html

e.g. you can do this:

import numpy as np
date_array = np.arange('2005-02', '2005-03', dtype='datetime64[D]')
date_array += np.timedelta64(4, 's')  # Add 4 seconds

If you have an array of seconds, you could convert it into an array of timedeltas and add that to a fixed datetime

Sign up to request clarification or add additional context in comments.

Comments

0

Say you have

seconds = [14084, 14085, 15003]

You can use pandas

import pandas as pd
series = pd.to_timedelta(seconds, unit='s') + pd.to_datetime('2011-11-11')
series = series.to_series().reset_index(drop=True)

print(series)
0   2011-11-11 03:54:44
1   2011-11-11 03:54:45
2   2011-11-11 04:10:03
dtype: datetime64[ns]

Or a list comprehension

list_comp = [datetime.datetime(2011, 11, 11) +
    datetime.timedelta(seconds=s) for s in seconds]

print(list_comp)
[datetime.datetime(2011, 11, 11, 3, 54, 44), datetime.datetime(2011, 11, 11, 3, 54, 45), datetime.datetime(2011, 11, 11, 4, 10, 3)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.