我想在Python中获取当前时间,并将它们分配到年、月、日、小时、分钟等变量中。在Python 2.7中如何做到这一点?


当前回答

import time
year = time.strftime("%Y") # or "%y"

其他回答

对于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

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对象上的属性具有您所需要的一切。

下面是一行代码,它的最大字符为80。

import time
year, month, day, hour, min = map(int, time.strftime("%Y %m %d %H %M").split())

您可以使用gmtime

from time import gmtime

detailed_time = gmtime() 
#returns a struct_time object for current time

year = detailed_time.tm_year
month = detailed_time.tm_mon
day = detailed_time.tm_mday
hour = detailed_time.tm_hour
minute = detailed_time.tm_min

注意:时间戳可以传递给gmtime,默认为当前时间 由时间返回()

eg.
gmtime(1521174681)

看到struct_time