如何在python中获得当前时间并分解为年,月,日,小时,分钟?

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

563880 次浏览

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对象的属性有你需要的一切。

通过解包datetime对象的timetuple,你应该得到你想要的:

from datetime import datetime


n = datetime.now()
t = n.timetuple()
y, m, d, h, min, sec, wd, yd, i = t

tzamandatetime回答要干净得多,但你可以用原始的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]

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

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

三个用于访问和操作日期和时间的库,即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]

这是一个老问题,但我想到了一个解决方案,我认为其他人可能会喜欢。

def get_current_datetime_as_dict():
n = datetime.now()
t = n.timetuple()
field_names = ["year",
"month",
"day",
"hour",
"min",
"sec",
"weekday",
"md",
"yd"]
return dict(zip(field_names, t))

Timetuple()可以与另一个数组压缩,该数组创建有标签的元组。将其转换为字典,生成的产品可以与get_current_datetime_as_dict()['year']一起使用。

这比这里的其他一些解决方案有更多的开销,但我发现能够在代码中为了清晰起见访问命名值是非常好的。

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)

您可以使用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,默认为当前时间 由time()

返回
eg.
gmtime(1521174681)

看到struct_time

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

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