1

I have a list of datetime containing year,month,day,hour,min,second and tzinfo, such as

In [1]:TimeCreate[0:4]
Out[1]:
[datetime.datetime(2011, 1, 1, 0, 0, 2),
 datetime.datetime(2011, 1, 1, 0, 2, 2),
 datetime.datetime(2011, 1, 1, 0, 27, 2),
 datetime.datetime(2011, 1, 1, 1, 0, 2)]

I only want to select date and hour in the datetime, therefore, I can have the first three items as one class, i.e, I can summarize the number of repetition under each hour. How could I obtain the following format?

In [2]:TimeCreate[0:4]
Out[2]:
[datetime.datetime(2011, 1, 1, 0),
 datetime.datetime(2011, 1, 1, 0),
 datetime.datetime(2011, 1, 1, 0),
 datetime.datetime(2011, 1, 1, 1)]

Therefore, I can have information, such as 3 repetition at hour 0.
Thank very much

TWord
  • 41
  • 5
  • have you checked http://stackoverflow.com/questions/5476065/truncate-python-datetime ? – glls May 20 '16 at 22:25

2 Answers2

2

Use datetime.replace,

import datetime

list_dt = [ datetime.datetime(2011, 1, 1, 0, 0, 2),
            datetime.datetime(2011, 1, 1, 0, 2, 2),
            datetime.datetime(2011, 1, 1, 0, 27, 2),
            datetime.datetime(2011, 1, 1, 1, 0, 2)] 

adjust_dt = [dt.replace(minute=0, second=0) for dt in list_dt] 

Use collections.Counter to count the frequency,

import collections

count = collections.Counter(adjust_dt)

print(count)
# Output
Counter({datetime.datetime(2011, 1, 1, 0, 0): 3, datetime.datetime(2011, 1, 1, 1, 0): 1})
SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
  • 1
    Thanks @sparkandshine, I created two-way table which gave the record for the repetition of a specific categorical variable (my object) under each hour from 01/01/2011 to 12/31/2015 by your solution. – TWord May 24 '16 at 15:49
0

you can extract anything from datetime.datetime class

import datetime

obj = datetime.datetime(2011, 1, 1, 0, 0, 2)

print(obj.day, obj.hour)

Ishaq Khan
  • 173
  • 2
  • 9