在python月中添加时间戳

时间:2011-07-22 10:38:53

标签: python

  

可能重复:
  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'})
dates.update({'2011-03-04':'16:03:01'})
dates.update({'2011-05-16':'16:03:01'})
dates.update({'2011-05-18':'16:03:01'})
dates.update({'2011-07-16':'16:03:01'})
dates.update({'2011-07-17':'16:03:01'})

从上面的字典中如何在python2.4

中添加特定月份的所有时间戳

2 个答案:

答案 0 :(得分:1)

可以在没有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'))

def month_stamps(stamps, month):
    return filter(lambda x: x.month == month, stamps)

print month_stamps(dates_list, 5)

答案 1 :(得分:0)

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 in sorted(months.keys()):
    print "Times for " + month + ": " + str(datetime.timedelta(seconds=months[month]))

输出:

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