如何在python中获取当前时间并将其分解为年、月、日、时、分?

2024-05-11 03:31:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到Python中的当前时间,并将它们赋给变量,如yearmonthdayhourminute。在Python2.7中如何做到这一点?


Tags: 时间yeardayhourmonthminute
3条回答

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

相关问题 更多 >