Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a program in Python to localize Asian timezone for a given dataframe
In Pandas, you can localize a DataFrame's datetime index to an Asian timezone using pd.date_range() with the tz parameter. This creates timezone-aware datetime indices for time series data.
Creating a Timezone-Localized DataFrame
To localize a DataFrame to an Asian timezone, follow these steps ?
Create a DataFrame with your data
Generate a timezone-aware datetime index using
pd.date_range()withtz='Asia/Calcutta'Assign the localized time index to the DataFrame's index
Syntax
time_index = pd.date_range(start, periods=n, freq='W', tz='Asia/Calcutta') df.index = time_index
Example
Let's create a DataFrame with Indian cities and localize it to Asia/Calcutta timezone ?
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'Id': [1, 2, 3, 4, 5],
'City': ['Mumbai', 'Pune', 'Delhi', 'Chennai', 'Kolkata']
})
# Create timezone-aware datetime index
time_index = pd.date_range('2020-01-01 00:30', periods=5, freq='W', tz='Asia/Calcutta')
# Assign the localized index to DataFrame
df.index = time_index
print("DataFrame is:")
print(df)
print("\nIndex is:")
print(df.index)
DataFrame is:
Id City
2020-01-05 00:30:00+05:30 1 Mumbai
2020-01-12 00:30:00+05:30 2 Pune
2020-01-19 00:30:00+05:30 3 Delhi
2020-01-26 00:30:00+05:30 4 Chennai
2020-02-02 00:30:00+05:30 5 Kolkata
Index is:
DatetimeIndex(['2020-01-05 00:30:00+05:30', '2020-01-12 00:30:00+05:30',
'2020-01-19 00:30:00+05:30', '2020-01-26 00:30:00+05:30',
'2020-02-02 00:30:00+05:30'],
dtype='datetime64[ns, Asia/Calcutta]', freq='W-SUN')
Key Parameters
start? Starting datetime for the rangeperiods? Number of periods to generatefreq? Frequency string ('W' for weekly, 'D' for daily, etc.)tz? Timezone name (e.g., 'Asia/Calcutta', 'Asia/Tokyo')
Other Asian Timezones
You can use different Asian timezone identifiers ?
import pandas as pd
# Different Asian timezones
timezones = ['Asia/Tokyo', 'Asia/Shanghai', 'Asia/Singapore']
for tz in timezones:
time_index = pd.date_range('2020-01-01 12:00', periods=2, freq='D', tz=tz)
print(f"{tz}:")
print(time_index)
print()
Asia/Tokyo: DatetimeIndex(['2020-01-01 12:00:00+09:00', '2020-01-02 12:00:00+09:00'], dtype='datetime64[ns, Asia/Tokyo]', freq='D') Asia/Shanghai: DatetimeIndex(['2020-01-01 12:00:00+08:00', '2020-01-02 12:00:00+08:00'], dtype='datetime64[ns, Asia/Shanghai]', freq='D') Asia/Singapore: DatetimeIndex(['2020-01-01 12:00:00+08:00', '2020-01-02 12:00:00+08:00'], dtype='datetime64[ns, Asia/Singapore]', freq='D')
Conclusion
Use pd.date_range() with the tz parameter to create timezone-localized DataFrame indices. The resulting DatetimeIndex will display the appropriate timezone offset for Asian timezones like Asia/Calcutta (+05:30).
