17 de mayo de 2016

44. Datetime. Locale

DATETIME, la fecha y la hora

La hora
Usando el módulo datetime podré obtener representación y datos de fechas y de horas. La clase time del módulo, se usa con las horas. Se pasa como argumento números enteros que representan horas, minutos, segundos y microsegundos.
# -*- coding: utf-8 -*-

import datetime

hora = datetime.time(14, 32, 55, 340)

print hora
print 'hora  :', hora.hour
print 'minut:', hora.minute
print 'segundo:', hora.second
print 'microsegundos:', hora.microsecond
print 'Información :', hora.tzinfo

print "Hora mínima: ", datetime.time.min
print "Hora máxima: ", datetime.time.max
print "Resolución: ", datetime.time.resolution
Pregunta. ¿Tiene sentido algún argumento pasado a la clase time de tipo float?
Se pueden usar los métodos min, max y resolution para saber cuál es la hora mínima, máxima y la resolución de conteo del tiempo del equipo.
= = =
La fecha
Pues se puede obtener también la fecha con datetime. Pero en este caso la clase date tiene un método llamado today() que obtiene la fecha actual. (¡Ojo! la clase time no tiene un método denominado now()).
# -*- coding: utf-8 -*-

import datetime

hoy = datetime.date.today()

print hoy
print 'ctime:', hoy.ctime()
print 'tupla:', hoy.timetuple()
print 'ordinal:', hoy.toordinal()
print 'Año:', hoy.year
print 'Mes :', hoy.month
print 'Día :', hoy.day

print "Día mínimo: ", datetime.date.min
print "Día máximo: ", datetime.date.max
print "Resolución: ", datetime.date.resolution
¿Tendrán tus programas una fecha de caducidad en Python? Razona tu respuesta.
= = =
Obtener fechas como el número de días desde eñ 1/1/0001 (ordinal) o por timestamp
# *-* coding:utf-8 *-*

import datetime

t = 735456

print datetime.date.fromordinal(t)

t = 119000000.4
#t = (2015-1970)*365*24*3600 + 11 * 31 * 24 * 3600 + 15 * 3600

print datetime.date.fromtimestamp(t)
¿Qué es el timestamp?
= = =
Escribir fechas directamente y con replace
# *-* coding:utf-8 *-*

import datetime

d1 = datetime.date(2008, 3, 12)
print 'd1:', d1

d2 = d1.replace(year=2009, month=4)
print 'd2:', d2
= = =
Establezco un timedelta
timedelta, o diferencia de tiempo, es una cantidad que establezco para después hacer cálculos.
# *-* coding:utf-8 *-*

import datetime

print "microsegundos:", datetime.timedelta(microseconds=1)
print "milisegundos:", datetime.timedelta(milliseconds=1)
print "segundos     :", datetime.timedelta(seconds=1)
print "minutos     :", datetime.timedelta(minutes=1)
print "horas       :", datetime.timedelta(hours=1)
print "días        :", datetime.timedelta(days=1)
print "semanas       :", datetime.timedelta(weeks=1)

print "semana, y tres días :", datetime.timedelta(weeks=1, days=3)
= = =
Aritmética de fechas
 *-* coding:utf-8 *-*

import datetime

hoy = datetime.date.today()

diferencia = datetime.timedelta(days=1)

print "Hoy es: ", hoy
print "Mañana será: ", hoy + diferencia
print "Ayer fue: ", hoy - diferencia
= = =
Comparando valores, de tiempo o de fecha
# *-* coding:utf-8 *-*

import datetime

hoy = datetime.date.today()

diferencia = datetime.timedelta(days=1)

print "Hoy es: ", hoy
print "Mañana será: ", hoy + diferencia
print "Ayer fue: ", hoy - diferencia

print "Hoy > ayer ", hoy > hoy - diferencia
print "Hoy < ayer ", hoy < hoy - diferencia

hora = datetime.time(12,34,56)
hora2 = datetime.time(12,43,56)

print hora, hora2

print "Despúes > ahora", hora2 > hora
= = =
La clase datetime.
Tenemos la clase time, la clase date y ahora... la clase datetime del módulo datetime.
# *-* coding:utf-8 *-*

import datetime

print 'Ahora    :', datetime.datetime.now()
print 'Hoy  :', datetime.datetime.today()
print 'Tiempo UTC:', datetime.datetime.utcnow()

d = datetime.datetime.now()
for attr in [ 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']:
    print attr, ':', getattr(d, attr)
Con esta clase podemos obtener una combinación de fecha y hora. Tenemos los métodos now, today y utcnow.
= = =
Crear una fecha y hora combinadas
La clase datetime también sirve para crear una fecha/hora combinadas
# -*- coding: utf-8 -*-

import datetime

hoy = datetime.date.today()

ahora = datetime.time(15,42,30)

print hoy, ahora

# combinando fecha y hora
combinadas = datetime.datetime.combine(hoy, ahora)
print combinadas

#  obteniendo formato fecha/hora desde ordinal y timestamp.
print datetime.datetime.fromordinal(384344)
print datetime.datetime.fromtimestamp(1232321321)
= = =
Formateando una fecha / una hora.
La representación que devuelve datetime sigue el estándar ISO-8601, pero puede modificarse para que muestre información de fecha/hora en un formato distinto. Para ello usa la función strftime.
# -*- coding: utf-8 -*-

import datetime

hoy = datetime.date.today()
formato = "%d-%m-%Y"
hoy_formateado = hoy.strftime(formato)
print hoy
print hoy_formateado
= = =
Y si tengo una instancia s que puede convertirse en timestamp, se puede usar datetime.datetime.strptime(s, format) para convertirlo en un objeto de la clase datetime.

Formateando fechas y horas. Módulo locale

%a Weekday as locale’s abbreviated name. Tue
%A Weekday as locale’s full name. Tuesday
%w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 2
%d Day of the month as a zero-padded decimal number. 03
%-d Day of the month as a decimal number. (Platform specific) 3
%b Month as locale’s abbreviated name. Sep
%B Month as locale’s full name. September
%m Month as a zero-padded decimal number. 09
%-m Month as a decimal number. (Platform specific) 9
%y Year without century as a zero-padded decimal number. 13
%Y Year with century as a decimal number. 2013
%H Hour (24-hour clock) as a zero-padded decimal number. 09
%-H Hour (24-hour clock) as a decimal number. (Platform specific) 9
%I Hour (12-hour clock) as a zero-padded decimal number. 09
%-I Hour (12-hour clock) as a decimal number. (Platform specific) 9
%p Locale’s equivalent of either AM or PM. AM
%M Minute as a zero-padded decimal number. 06
%-M Minute as a decimal number. (Platform specific) 6
%S Second as a zero-padded decimal number. 05
%-S Second as a decimal number. (Platform specific) 5
%f Microsecond as a decimal number, zero-padded on the left. 000000
%z UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).
%Z Time zone name (empty string if the object is naive).
%j Day of the year as a zero-padded decimal number. 246
%-j Day of the year as a decimal number. (Platform specific) 246
%U Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. 35
%W Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. 35
%c Locale’s appropriate date and time representation. Tue Sep 3 09:06:05 2013
%x Locale’s appropriate date representation. 09/03/13
%X Locale’s appropriate time representation. 09:06:05
%% A literal '%' character. %
= = =
Usando locale para obtener información del idioma del usuario por defecto
Más información en el módulo locale.
# -*- coding: utf-8 -*-

import locale, datetime

locale.setlocale(locale.LC_ALL, '')

hoy = datetime.date.today()

formato = "%a,%b %d-%m-%Y"

hoy_formateado = hoy.strftime(formato)

print hoy
print hoy_formateado

No hay comentarios:

Publicar un comentario