Techno Blender
Digitally Yours.

Handling time zones with Python. This post demonstrates the… | by Himalaya Bir Shrestha | Apr, 2023

0 45


Illustration of different time zones in the world. Map © OpenStreetMap contributors. Labels added by Author.
Image by Luis Cortes in Unsplash.

Geocoding to retrieve the coordinates of four cities

from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="app")

def get_coordinates(place):
"""Return the latitude and longitude of the place."""
place_details = geolocator.geocode(place)
coordinates = (place_details[1][0], place_details[1][1])

return coordinates

Dataframe is created containing latitude and longitude values of the four cities. Illustration by Author.

Accessing data using NASA Power API

base_url = r”https://power.larc.nasa.gov/api/temporal/hourly/point?parameters=ALLSKY_SFC_SW_DWN&community=RE&time-standard=UTC&longitude={longitude}&latitude={latitude}&format=JSON&start=2020&end=2020"

Parameter description

Equation 1 and 2 refer to formula for calculating the sizes of solar PV module and battery to meet given electricity demand based on solar irradiance and other technical parameters. Illustration by Author.

Basic statistics of given data

Global Horizontal Irradiance data downloaded for four cities. Illustration by Author.
Statistics from the downloaded data. Illustration by Author.

Time zone Handling

1. Default pandas dataframe without “datetime” format index

Data when first downloaded from NASA Power website. Illustration by Author.

2. Converting integer type index to “naive” datetime index

Converting integer index to datetime index. Illustration by Author.
Plotting pandas dataframe with “naive” datetime index shows months from Jan to Dec 2020 in the xaxis. Illustration by Author.
Checking the time zone info of the first datetime index of dataframe. Illustration by Author.

3. Localizing “naive” datetime object to “time zone aware” datetime object

First cell shows the current local time time_now as a naive datetime object without time zone information. Second cell shows localizing time_now to Nepali time zone. Third cell shows converting Nepali local time to German local time. Illustration by Author.

4. Localizing timezone of pandas dataframe

Localizing naive dataframe index to UTC time zone. Illustration by Author.

5. List of all possible time zone addresses

List of possible addresses that can be referred to for time zones using pytz module. Illustration by Author.

6. Create new dataframe for each city and convert UTC time zone to corresponding local time zone

Creating different dataframes out of each column of df. The time zones of new dataframes are converted from UTC to respective time zone of the country/city.

7. Comparing the plots of solar irradiance data in different time zones

fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (20, 6))
fig.suptitle("Solar irradiance on October 1, 2020")

ax1.plot(df.loc["2020–10–01"])
ax1.set_title("Based on UTC time zone")
ax1.xaxis.set_ticks(ticks = df.loc["2020–10–01"].index[::4], labels = np.arange(0, 24, 4))

cities = df.columns.tolist()
handles = ax1.get_legend_handles_labels()[0]
ax1.legend(handles, labels = cities, loc = "upper right")
ax1.set_xlabel("Hour of day")
ax1.set_ylabel("W/m$^2$")

ax2.plot(df_chitwan.loc["2020–10–01"].values.tolist())
ax2.plot(df_newyork.loc["2020–10–01"].values.tolist())
ax2.plot(df_bonn.loc["2020–10–01"].values.tolist())
ax2.plot(df_sydney.loc["2020–10–01"].values.tolist())
ax2.xaxis.set_ticks(ticks = np.arange(0, 24, 4), labels = np.arange(0, 24, 4))

handles = ax2.get_legend_handles_labels()[0]
ax2.legend(handles, labels = cities)
ax2.set_title("Based on local time zone of each city/country")
ax2.set_xlabel("Hour of day")
ax2.set_ylabel("W/m$^2$")

plt.savefig("output/solar irradiance on october 1.jpeg",
dpi = 300)
plt.show()

Solar irradiance on October 1, 2020. Left: Based on UTC time zone. Right: Based on local time zone of each city/country. Illustration by Author.
time_in_nepal =  timezone("Asia/Kathmandu”).localize(datetime.now()) 
german_timezone = timezone(“Europe/Berlin”)
time_in_germany = time_in_nepal.astimezone(german_timezone)
df_utc = df.tz_localize(tz = “UTC”)
df_nepal = df_utc.tz_convert(tz = “Asia/Kathmandu”)


Illustration of different time zones in the world. Map © OpenStreetMap contributors. Labels added by Author.
Image by Luis Cortes in Unsplash.

Geocoding to retrieve the coordinates of four cities

from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="app")

def get_coordinates(place):
"""Return the latitude and longitude of the place."""
place_details = geolocator.geocode(place)
coordinates = (place_details[1][0], place_details[1][1])

return coordinates

Dataframe is created containing latitude and longitude values of the four cities. Illustration by Author.

Accessing data using NASA Power API

base_url = r”https://power.larc.nasa.gov/api/temporal/hourly/point?parameters=ALLSKY_SFC_SW_DWN&community=RE&time-standard=UTC&longitude={longitude}&latitude={latitude}&format=JSON&start=2020&end=2020"

Parameter description

Equation 1 and 2 refer to formula for calculating the sizes of solar PV module and battery to meet given electricity demand based on solar irradiance and other technical parameters. Illustration by Author.

Basic statistics of given data

Global Horizontal Irradiance data downloaded for four cities. Illustration by Author.
Statistics from the downloaded data. Illustration by Author.

Time zone Handling

1. Default pandas dataframe without “datetime” format index

Data when first downloaded from NASA Power website. Illustration by Author.

2. Converting integer type index to “naive” datetime index

Converting integer index to datetime index. Illustration by Author.
Plotting pandas dataframe with “naive” datetime index shows months from Jan to Dec 2020 in the xaxis. Illustration by Author.
Checking the time zone info of the first datetime index of dataframe. Illustration by Author.

3. Localizing “naive” datetime object to “time zone aware” datetime object

First cell shows the current local time time_now as a naive datetime object without time zone information. Second cell shows localizing time_now to Nepali time zone. Third cell shows converting Nepali local time to German local time. Illustration by Author.

4. Localizing timezone of pandas dataframe

Localizing naive dataframe index to UTC time zone. Illustration by Author.

5. List of all possible time zone addresses

List of possible addresses that can be referred to for time zones using pytz module. Illustration by Author.

6. Create new dataframe for each city and convert UTC time zone to corresponding local time zone

Creating different dataframes out of each column of df. The time zones of new dataframes are converted from UTC to respective time zone of the country/city.

7. Comparing the plots of solar irradiance data in different time zones

fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (20, 6))
fig.suptitle("Solar irradiance on October 1, 2020")

ax1.plot(df.loc["2020–10–01"])
ax1.set_title("Based on UTC time zone")
ax1.xaxis.set_ticks(ticks = df.loc["2020–10–01"].index[::4], labels = np.arange(0, 24, 4))

cities = df.columns.tolist()
handles = ax1.get_legend_handles_labels()[0]
ax1.legend(handles, labels = cities, loc = "upper right")
ax1.set_xlabel("Hour of day")
ax1.set_ylabel("W/m$^2$")

ax2.plot(df_chitwan.loc["2020–10–01"].values.tolist())
ax2.plot(df_newyork.loc["2020–10–01"].values.tolist())
ax2.plot(df_bonn.loc["2020–10–01"].values.tolist())
ax2.plot(df_sydney.loc["2020–10–01"].values.tolist())
ax2.xaxis.set_ticks(ticks = np.arange(0, 24, 4), labels = np.arange(0, 24, 4))

handles = ax2.get_legend_handles_labels()[0]
ax2.legend(handles, labels = cities)
ax2.set_title("Based on local time zone of each city/country")
ax2.set_xlabel("Hour of day")
ax2.set_ylabel("W/m$^2$")

plt.savefig("output/solar irradiance on october 1.jpeg",
dpi = 300)
plt.show()

Solar irradiance on October 1, 2020. Left: Based on UTC time zone. Right: Based on local time zone of each city/country. Illustration by Author.
time_in_nepal =  timezone("Asia/Kathmandu”).localize(datetime.now()) 
german_timezone = timezone(“Europe/Berlin”)
time_in_germany = time_in_nepal.astimezone(german_timezone)
df_utc = df.tz_localize(tz = “UTC”)
df_nepal = df_utc.tz_convert(tz = “Asia/Kathmandu”)

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.
Leave a comment