¿Quién no enfrenta problemas cuando no tiene sus dispositivos o su teléfono para ver la hora actual? Me he enfrentado a este tipo de problemas, cuando salí y en el proceso me olvidé de llevar mi móvil. Este artículo trata sobre la hora, la fecha, las zonas horarias y también la hora actual en Python. Las conversiones de tiempo pueden ser bastante aburridas y tediosas, pero Python es un gran respiro. Entonces, ahora entremos directamente en la comprensión de los conceptos de fecha y hora en Python.
El módulo del péndulo
El péndulo es un zona horaria biblioteca que facilita la manipulación de fecha y hora. Es similar al módulo datetime, que veremos un poco más adelante. El módulo de péndulo también ofrece un método now() que devuelve la fecha y la hora locales.
Pendulum se puede instalar fácilmente usando el comando PIP:
pip install pendulum
Ejemplo,
import pendulum time = pendulum.now() print(time)
Producción:
2021-04-26 20:07:22.940108+05:30
Como se mencionó anteriormente, el método now() devuelve la fecha y la hora actuales, como podemos ver en el resultado anterior.
Fecha y hora actual en Python
Python también ofrece una gran cantidad de características de confiabilidad y usabilidad de código multiplataforma. En la mayoría de los casos, por lo tanto, el usuario necesita la fecha o la hora para una zona horaria específica y el uso de algunos módulos como pytz y pendulum facilita mucho el trabajo en dicho entorno.
Tenga en cuenta que el módulo pytz trae la base de datos Olson tz a Python. Permite cálculos de zona horaria precisos y multiplataforma.
pip install pytz
Ejemplo
Ahora tomemos un ejemplo en el que tratamos de obtener y luego imprimir la fecha y la hora para diferentes zonas horarias. Esto se hará usando el módulo pytz y el péndulo.
import pytz from datetime import datetime utc = pytz.timezone('UTC') pst = pytz.timezone('America/Los_Angeles') ist = pytz.timezone('Asia/Calcutta') print("Using pytz Module:") print('Current Date and Time in UTC =', datetime.now(utc)) print('Current Date and Time in PST =', datetime.now(pst)) print('Current Date and Time in IST =', datetime.now(ist)) import pendulum utc1 = pendulum.timezone('UTC') pst1 = pendulum.timezone('America/Los_Angeles') ist1 = pendulum.timezone('Asia/Calcutta') print("Using pendulum Module:") print('Current Date Time in UTC =', datetime.now(utc1)) print('Current Date Time in PST =', datetime.now(pst1)) print('Current Date Time in IST =', datetime.now(ist1))
Producción
Using pytz Module: Current Date and Time in UTC = 2021-04-26 15:44:53.074040+00:00 Current Date and Time in PST = 2021-04-26 08:44:53.090041-07:00 Current Date and Time in IST = 2021-04-26 21:14:53.126043+05:30 Using pendulum Module: Current Date Time in UTC = 2021-04-26 15:44:56.888258+00:00 Current Date Time in PST = 2021-04-26 08:44:56.889258-07:00 Current Date Time in IST = 2021-04-26 21:14:56.889258+05:30
Aquí,
- Para ambos casos, primero usamos la función timezone() definida para los módulos pytz y pendulum mientras pasamos la zona horaria requerida
- Luego pasamos estos objetos de zona horaria a la función now(). . El método devuelve una fecha y hora precisas para la zona horaria dada.
El módulo “datetime” — Hora actual en Python
Este módulo proporciona clases para manipular fechas y horas en Python.
En el ejemplo proporcionado a continuación, intentamos ejecutar varias operaciones en la fecha y la hora. Como buscar la fecha actual y la hora actual y otras cosas similares, usando métodos y funciones como hoy(), ahora(), hora, etc.
Ejemplos misceláneos usando el módulo de fecha y hora
import time from datetime import datetime def main(): print('*** Get Current date & timestamp using datetime.now() ***') # Returns a datetime object containing the local date and time dateTimeObj = datetime.now() # Access the member variables of datetime object to print date & time information print(dateTimeObj.year, '/', dateTimeObj.month, '/', dateTimeObj.day) print(dateTimeObj.hour, ':', dateTimeObj.minute, ':', dateTimeObj.second, '.', dateTimeObj.microsecond) print(dateTimeObj) # Converting datetime object to string timestampStr = dateTimeObj.strftime("%d-%b-%Y (%H:%M:%S.%f)") print('Current Timestamp : ', timestampStr) timestampStr = dateTimeObj.strftime("%H:%M:%S.%f - %b %d %Y ") print('Current Timestamp : ', timestampStr) print('*** Fetch the date only from datetime object ***') # get the date object from datetime object dateObj = dateTimeObj.date() # Print the date object print(dateObj) # Access the member variables of date object to print print(dateObj.year, '/', dateObj.month, '/', dateObj.day) # Converting date object to string dateStr = dateObj.strftime("%b %d %Y ") print(dateStr) print('*** Fetch the time only from datetime object ***') # get the time object from datetime object timeObj = dateTimeObj.time() # Access the member variables of time object to print time information print(timeObj.hour, ':', timeObj.minute, ':', timeObj.second, '.', timeObj.microsecond) # It contains the time part of the current timestamp, we can access it's member variables to get the fields or we can directly print the object too print(timeObj) # Converting date object to string timeStr = timeObj.strftime("%H:%M:%S.%f") print(timeStr) print('*** Get Current Timestamp using time.time() ***') # Get the seconds since epoch secondsSinceEpoch = time.time() print('Seconds since epoch : ', secondsSinceEpoch) # Convert seconds since epoch to struct_time timeObj = time.localtime(secondsSinceEpoch) print(timeObj) # get the current timestamp elements from struct_time object i.e. print('Current TimeStamp is : %d-%d-%d %d:%d:%d' % ( timeObj.tm_mday, timeObj.tm_mon, timeObj.tm_year, timeObj.tm_hour, timeObj.tm_min, timeObj.tm_sec)) # It does not have the microsecond field print('*** Get Current Timestamp using time.ctime() *** ') timeStr = time.ctime() print('Current Timestamp : ', timeStr) if __name__ == '__main__': main()
Producción :
*** Get Current date & timestamp using datetime.now() *** 2021 / 4 / 26 20 : 24 : 10 . 371305 2021-04-26 20:24:10.371305 Current Timestamp : 26-Apr-2021 (20:24:10.371305) Current Timestamp : 20:24:10.371305 - Apr 26 2021 *** Fetch the date only from datetime object *** 2021-04-26 2021 / 4 / 26 Apr 26 2021 *** Fetch the time only from datetime object *** 20 : 24 : 10 . 371305 20:24:10.371305 20:24:10.371305 *** Get Current Timestamp using time.time() *** Seconds since epoch : 1619448851.1463068 time.struct_time(tm_year=2021, tm_mon=4, tm_mday=26, tm_hour=20, tm_min=24, tm_sec=11, tm_wday=0, tm_yday=116, tm_isdst=0) Current TimeStamp is : 26-4-2021 20:24:11 *** Get Current Timestamp using time.ctime() *** Current Timestamp : Mon Apr 26 20:24:11 2021
Eche un vistazo aquí para ver el programa del día de la semana con la biblioteca de fecha y hora.
CONCLUSIÓN
A través de esta publicación, hemos adquirido una comprensión profunda de los diversos módulos relacionados con la fecha y la hora y sus diversas funciones y métodos. También vimos cómo instalar y trabajar con varias bibliotecas como pytz, pendulum y datetime. Así pues, ahora supongo y espero que el tema que nos ocupa os quede bastante claro. Desde entonces, hemos cubierto el tema en gran profundidad con la ayuda de numerosos ejemplos interesantes.