¿Cómo obtener la hora actual en Python y dividirla en año, mes, día, hora y minuto?

Resuelto guagay_wk asked hace 9 años • 10 respuestas

Me gustaría obtener la hora actual en Python y asignarla a variables como year,,,, . ¿Cómo se puede hacer esto en Python 2.7?monthdayhourminute

guagay_wk avatar May 06 '15 15:05 guagay_wk
Aceptado

El datetimemódulo es tu amigo:

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

No necesita variables separadas, los atributos del datetimeobjeto devuelto tienen todo lo que necesita.

tzaman avatar May 06 '2015 08:05 tzaman

Aquí hay una frase que viene justo por debajo de la línea de 80 caracteres como máximo.

import time
yr, month, day, hr, minute = map(int, time.strftime("%Y %m %d %H %M").split())
rigsby avatar Dec 20 '2016 20:12 rigsby

La datetimerespuesta de tzaman es mucho más clara, pero puedes hacerlo con el timemódulo original de Python:

import time
strings = time.strftime("%Y,%m,%d,%H,%M,%S")
t = strings.split(',')
numbers = [ int(x) for x in t ]
print numbers

Producción:

[2016, 3, 11, 8, 29, 47]
vossman77 avatar Mar 11 '2016 14:03 vossman77

Al descomprimir timetupleel objeto datetime, deberías obtener lo que deseas:

from datetime import datetime

n = datetime.now()
t = n.timetuple()
y, m, d, h, min, sec, wd, yd, i = t
ljk321 avatar May 06 '2015 08:05 ljk321