1

I have and excel file that contains lists like this:

month   day     time
1        1      00:00
1        2      02:00
1        3      08:00
2        1      19:00
2        2      04:00

I need them to be python datetime objects like this (1,1,00:00),(1,2,02:00)...

Can anyone help?

Copy from comment: I have done this:

Dates={'month': [val[0] for val in datain], 
       'day': [val[1] for val in datain], 
       'time': [val[2] for val in datain]} 
df=DataFrame(Dates, columns= ['day', 'month','time']) 

and it gives out this:

day month time 
0 1 10 0.000000 
1 1 10 0.041667 
2 1 10 0.083333 
3 1 10 0.125000 
4 1 10 0.166667 
5 1 10 0.208333 
6 1 10 0.250000 
7 1 10 0.291667 
8 1 10 0.333333 

I need to merge them together now and get the time right.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Can you show your current attempt please? I would suggest having a look at the [pandas](https://pandas.pydata.org/) library as a first place to look. – FChm Feb 23 '19 at 16:44
  • Relevant [convert-pandas-column-to-datetime](https://stackoverflow.com/questions/26763344/convert-pandas-column-to-datetime) – stovfl Feb 23 '19 at 17:20

2 Answers2

0

With to_datetime you can convert any column to pandas datetime very easily.

df['fulldate'] = df['month'].astype(str)+'/'+df['day'].astype(str)+'/'+df['time']

# Careful, there's not year in the data frame you gave
df['fulldate'] = pd.to_datetime(df['fulldate'], format='%m/%d/%H:%M')

If you want a plain datetimeobject, you can use

df['fulldate'].apply(lambda x: x.to_pydatetime())

# OR

df['fulldate'].dt.to_pydatetime()

If plain datetime object really are your concern, here are some run timers (10k rows):

pd.to_datetime(df['fulldate'], format='%m/%d/%H:%M').dt.to_pydatetime()
#220 ms ± 6.51 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

df['fulldate'].apply(lambda date: datetime.strptime(date, '%m/%d/%H:%M'))
#879 ms ± 289 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
RobinFrcd
  • 4,439
  • 4
  • 25
  • 49
0

Try this

from datetime import datetime
import csv
output = []
with open('./test_time.csv') as f:
    rows = csv.DictReader(f)
    for r in rows:
        t1, t2 = r['time'].split(':')
        m = int(r['month'])
        d = int(r['day'])
        y = datetime.today().year
        output.append(datetime(y, m, d, int(t1), int(t2)))
print(output)
Nada Ghanem
  • 451
  • 6
  • 16