Reputation: 19
I have a code where I get date and time of different parts of the world with the datetime and zoneinfo libraries in Python. I am able to extract the dates and hourse separately in day, month, year, hour, minute, second and microsecond, but I don't know hoe to extract the Time Zone part of the datetime variable I got. Part of the code is as follows:
import datetime
import zoneinfo
zonaNewYork = zoneinfo.ZoneInfo('America/New_York')
fechaHora_NewYork = datetime.datetime.now(zonaNewYork)
print(type(fechaHora_NewYork))
print("Fecha y Hora en NewYork, EEUU: ")
print(fechaHora_NewYork, "\n")
###### Get Time individually
hora = fechaHora_NewYork.hour
print("Hora: ", hora, "\n")
minutos = fechaHora_NewYork.minute
print("Minutos: ", minutos, "\n")
segundos = fechaHora_NewYork.second
print("Segundos: ", segundos, "\n")
microsegundos = fechaHora_NewYork.microsecond
print("Microsegundos: ",microsegundos, "\n")
###### Get Date individually
year = horafecha_actual.year
print("Año: ", year, "\n")
mes = horafecha_actual.month
print("Mes: ", mes, "\n")
dia = horafecha_actual.day
print("Día: ", dia, "\n")
The code ouputs this:
<class 'datetime.datetime'>
Fecha y Hora en NewYork, EEUU:
2024-07-01 17:32:11.454840-04:00
Hora: 17
Minutos: 32
Segundos: 11
Microsegundos: 454840
Año: 2024
Mes: 7
Día: 1
So the question is, how do I get the "-4:00" from "2024-07-01 17:32:11.454840-04:00"?
Thanks in advance
Upvotes: 0
Views: 74
Reputation: 58589
import datetime
import zoneinfo
zonaNewYork = zoneinfo.ZoneInfo('America/New_York')
fechaHora_NewYork = datetime.datetime.now(zonaNewYork)
print(fechaHora_NewYork.strftime('%:z')) # <--- since py 3.12
You can do it yourself, too, by interrogating the tzinfo
member of a datetime
object: fechaHora_NewYork.tzinfo
Upvotes: 0