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


当前回答

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

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

其他回答

对于python 3

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)

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]

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

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

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())