时区转换是你们常常遇到的问题,本文的代码能够实现如下功能:html
软件包:python
timezonefinder 可根据所给的经纬度找到对应的时区信息。为节省计算时间,能够提早将相应的时区信息读入内存中,也即设置in_memory=True。git
# Import packages
from timezonefinder import TimezoneFinder
import pandas as pd
# Find timezone based on longitude and latitude
tf = TimezoneFinder(in_memory=True)
longitude = -88
latitude = 36
local_time_zone = tf.timezone_at(lng=longitude, lat=latitude)
local_time_zone
复制代码
'America/Chicago'
复制代码
此处,咱们利用pandas date_range函数建立了一个4小时间隔的时间序列。api
# Create naive timestamps using pandas
test_naive = pd.date_range('2019-04-06', '2019-04-07', freq='4H')
test_naive
复制代码
DatetimeIndex(['2019-04-06 00:00:00', '2019-04-06 04:00:00',
'2019-04-06 08:00:00', '2019-04-06 12:00:00',
'2019-04-06 16:00:00', '2019-04-06 20:00:00',
'2019-04-07 00:00:00'],
dtype='datetime64[ns]', freq='4H')
复制代码
以上输出显示的时间序列是没有时区信息的,咱们此处假设上面的时区是UTC,而后咱们能够给它加上时区信息,所用到的函数是 tz_localize。微信
# Set time to be UTC
test_UTC = test_naive.tz_localize('UTC')
test_UTC
复制代码
DatetimeIndex(['2019-04-06 00:00:00+00:00', '2019-04-06 04:00:00+00:00',
'2019-04-06 08:00:00+00:00', '2019-04-06 12:00:00+00:00',
'2019-04-06 16:00:00+00:00', '2019-04-06 20:00:00+00:00',
'2019-04-07 00:00:00+00:00'],
dtype='datetime64[ns, UTC]', freq='4H')
复制代码
如今上面的时间序列已经有时区信息了,也即+00:00。 此时咱们就能够利用pandas里的tz_convert 将UTC时间转换为任意时区的时间。函数
# Convert UTC to local time
test_local = test_UTC.tz_convert(local_time_zone)
test_local
复制代码
DatetimeIndex(['2019-04-05 19:00:00-05:00', '2019-04-05 23:00:00-05:00',
'2019-04-06 03:00:00-05:00', '2019-04-06 07:00:00-05:00',
'2019-04-06 11:00:00-05:00', '2019-04-06 15:00:00-05:00',
'2019-04-06 19:00:00-05:00'],
dtype='datetime64[ns, America/Chicago]', freq='4H')
复制代码
输出显示以上已经转化为 -05:00。有时候咱们还须要将时间格式转换为原来的样式,也就是没有时区信息的格式,这时咱们还能够用 tz_localize 这个函数,不过此时参数应该是None。spa
# Convert back to naive timestamps, but in local time zone.
test_local_naive = test_local.tz_localize(None)
test_local_naive
复制代码
DatetimeIndex(['2019-04-05 19:00:00', '2019-04-05 23:00:00',
'2019-04-06 03:00:00', '2019-04-06 07:00:00',
'2019-04-06 11:00:00', '2019-04-06 15:00:00',
'2019-04-06 19:00:00'],
dtype='datetime64[ns]', freq='4H')
复制代码
总结一下:code
微信公众号:测度空间htm