¿Cómo obtener la hora actual en Python y dividirla en año, mes, día, hora y minuto?
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?month
day
hour
minute
Aceptado
El datetime
mó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 datetime
objeto devuelto tienen todo lo que necesita.
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())
La datetime
respuesta de tzaman es mucho más clara, pero puedes hacerlo con el time
mó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]
Al descomprimir timetuple
el 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