我想在Python中获取当前时间,并将它们分配到年、月、日、小时、分钟等变量中。在Python 2.7中如何做到这一点?
当前回答
import time
year = time.strftime("%Y") # or "%y"
其他回答
datetime模块是你的朋友:
import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40
您不需要单独的变量,返回的datetime对象上的属性具有您所需要的一切。
对于python 3
import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
通过解包datetime对象的timetuple,你应该得到你想要的:
from datetime import datetime
n = datetime.now()
t = n.timetuple()
y, m, d, h, min, sec, wd, yd, i = t
import time
year = time.strftime("%Y") # or "%y"
tzaman的datetime回答要干净得多,但你可以用原始的python time模块来做:
import time
strings = time.strftime("%Y,%m,%d,%H,%M,%S")
t = strings.split(',')
numbers = [ int(x) for x in t ]
print numbers
输出:
[2016, 3, 11, 8, 29, 47]