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

use*_*486 254 python time datetime python-2.7

我想获得当前时间在Python,并将它们分配到像变量year,month,day,hour,minute.如何在Python 2.7中完成?

tza*_*man 456

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
Run Code Online (Sandbox Code Playgroud)

您不需要单独的变量,返回datetime对象上的属性就可以满足您的所有要求.

  • 只是补充:`import time \n now=time.localtime() \n print now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_hour, now.tm_min, now.tm_sec, now.tm_wday , now.tm_yday, now.tm_isdst` (6认同)

vos*_*n77 27

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
Run Code Online (Sandbox Code Playgroud)

输出:

[2016, 3, 11, 8, 29, 47]
Run Code Online (Sandbox Code Playgroud)


rig*_*sby 25

这是一个单线程,最高可达80 char线.

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


sky*_*489 14

通过解压缩timetupledatetime对象,您应该得到您想要的:

from datetime import datetime

n = datetime.now()
t = n.timetuple()
y, m, d, h, min, sec, wd, yd, i = t
Run Code Online (Sandbox Code Playgroud)

  • 注意:您正在隐藏内置函数“min” (3认同)

Taj*_*idi 6

对于python 3

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
Run Code Online (Sandbox Code Playgroud)


xia*_*eiz 5

import time
year = time.strftime("%Y") # or "%y"
Run Code Online (Sandbox Code Playgroud)


Sre*_*A R 5

您可以使用 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
Run Code Online (Sandbox Code Playgroud)

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

eg.
gmtime(1521174681)
Run Code Online (Sandbox Code Playgroud)

参见struct_time


Tom*_*vid 5

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

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)
Run Code Online (Sandbox Code Playgroud)

结果:

day_month_year: 2019-03-26
Run Code Online (Sandbox Code Playgroud)