从以下日期开始,如何使用python
获取月份和年份日期
"2011-07-01 09:26:11" //This showud display as "This month"
"2011-06-07 09:26:11" //This should display as June
"2011-03-12 09:26:11" //This should display as March
"2010-07-25 09:26:11" // Should display as last year
请告诉我如何使用python 2.4获取这些格式
当我在pandas dataframe中有一个[具有相同格式]的日期变量时,如何执行此操作?
答案 0 :(得分:4)
import time
import calendar
current = time.localtime()
dates = ["2011-07-01 09:26:11", "2011-06-07 09:26:11", "2011-03-12 09:26:11", "2010-07-25 09:26:11"]
for date in dates:
print "%s" % date
date = time.strptime(date, "%Y-%m-%d %H:%M:%S")
if date.tm_year == current.tm_year - 1:
print "Last year"
elif date.tm_mon == current.tm_mon:
print "This month"
else:
print calendar.month_name[date.tm_mon]
应该大致按照你的要求做。
答案 1 :(得分:2)
from datetime import datetime
a = datetime.strptime('2011-07-01 09:26:11', '%Y-%m-%d %H:%M:%S')
if a.month == datetime.now().month:
print 'This month'
的其他结果
答案 2 :(得分:0)
python日期/时间转换的良好网站: http://www.saltycrane.com/blog/2008/11/python-datetime-time-conversions/
答案 3 :(得分:-2)
您可以使用datetime.strptime粘贴日期。 但对于像你这样的简单案例,我只会使用正则表达式。
>>>> import re
>>>> re.match('^(\d+)-(\d+)', "2011-07-01 09:26:11").groups()
('2011', '07')