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


当前回答

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

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

其他回答

让我们看看如何从当前时间中获取并打印日、月、年:

import datetime

now = datetime.datetime.now()
year = '{:02d}'.format(now.year)
month = '{:02d}'.format(now.month)
day = '{:02d}'.format(now.day)
hour = '{:02d}'.format(now.hour)
minute = '{:02d}'.format(now.minute)
day_month_year = '{}-{}-{}'.format(year, month, day)

print('day_month_year: ' + day_month_year)

结果:

day_month_year: 2019-03-26
import time
year = time.strftime("%Y") # or "%y"

三个用于访问和操作日期和时间的库,即datetime、arrow和pendulum,都使这些项在命名元组中可用,其元素可以通过名称或索引访问。此外,物品以完全相同的方式访问。(我想如果我更聪明的话,我就不会感到惊讶了。)

>>> YEARS, MONTHS, DAYS, HOURS, MINUTES = range(5)
>>> import datetime
>>> import arrow
>>> import pendulum
>>> [datetime.datetime.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [arrow.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [pendulum.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 16]

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