在python中按月添加时间戳
可能重复:在python中按月添加时间戳,python,Python,可能重复: 从上面的字典中了解如何在python2.4 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)) i
从上面的字典中了解如何在
python2.4
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
无需正则表达式即可解决此问题:
# 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)
这个场景与那个场景非常不同,这就是我发布新帖子的原因。其实没什么不同。。。但好吧,如果我能从那里回收我的代码,没问题:)是的,但我认为这会非常不同:)@Rajeev:你不能“认为”这会非常不同。在问题中,你必须以不同的方式写作。请编辑此问题以解释其不同之处。哎呀,我刚刚修复了一个错误(使用
str
而不是repr
)。stamps=[datetime.strTime(“%s%s%”(日期,时间),“%Y-%m-%d%H:%m:%s”)表示日期,时间表示日期。iteritems()
和返回[stamps for stamps if stamps if stamps.month==month]
和打印月份邮票(邮票,5)
# 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)