Skip to content Skip to sidebar Skip to footer

Add Timestamps In Python Month Wise

Possible Duplicate: Add timestamps in python dates = {} dates.update({'2011-03-07':'16:03:01'}) dates.update({'2011-03-06':'16:03:01'}) dates.update({'2011-03-08':'16:03:01'})

Solution 1:

It may be solved without RegExps:

# dates = { ... } from datetime import datetime

stamps = []
for date, time in dates.iteritems():
    stamps.append(datetime.strptime('%s %s' % (date, time), '%Y-%m-%d %H:%M:%S'))

defmonth_stamps(stamps, month):
    returnfilter(lambda x: x.month == month, stamps)

print month_stamps(dates_list, 5)

Solution 2:

import datetime
import re
months = {}
for date in dates:
    month = date[:7]
    time = re.match(r"(\d+):(\d+):(\d+)", dates[date])
    seconds = int(time.group(1))*3600 + int(time.group(2))*60 + int(time.group(3))
    if month in months:
        months[month] += seconds
    else:
        months[month] = seconds
for month insorted(months.keys()):
    print"Times for " + month + ": " + str(datetime.timedelta(seconds=months[month]))

Output:

Times for 2011-03:2days,16:12:04Times for 2011-05:1day,8:06:02Times for 2011-07:1day,8:06:02

Post a Comment for "Add Timestamps In Python Month Wise"