Folium TimestampedGeoJson无法按每月1日步进时间轴问题
Folium TimestampedGeoJson时间轴偏离预设日期问题解决(夏令时相关)
问题描述
使用Folium的TimestampedGeoJson插件绘制每月1日的LineString时,时间轴出现异常:预设日期均为每月1日,但从11月1日开始跳至11月30日,后续持续偏离,直到次年4月1日才恢复。尝试将dates替换为times、调整period和duration参数均无效;移除period后,时间轴在切换时出现当日23点的跳变,推测是夏令时导致的时区偏移问题。需要让插件忽略夏令时,完全遵循预设的时间戳驱动时间轴。
解决方案
1. 强制使用UTC时间戳
将所有时间字符串末尾添加Z标记,指定为UTC时间,避免本地时区的夏令时转换影响。UTC时间没有夏令时变化,能确保时间轴计算完全匹配预设日期。
修改后的时间示例:
"dates": ["2017-09-01T00:00:00Z", "2017-10-01T00:00:00Z"]
2. 关闭自动时间周期推算,完全使用自定义时间戳
移除period参数,同时设置add_last_point=False,让插件直接读取所有Feature的times字段生成时间轴,而非自动推算步进。这样时间轴会完全遵循你预设的每月1日节点。
修改后的TimestampedGeoJson初始化代码:
TimestampedGeoJson( pipelines, add_last_point=False ).add_to(m)
完整修改后代码
import folium from folium.plugins import TimestampedGeoJson def create_geojson() -> dict: lines: list = [ {"coordinates": [[139.76451, 35.68159],[139.75964, 35.68259]], "dates": ["2017-09-01T00:00:00Z", "2017-10-01T00:00:00Z"]}, {"coordinates": [[139.76451, 35.68159],[139.75964, 35.68259]], "dates": ["2017-10-01T00:00:00Z", "2017-11-01T00:00:00Z"]}, {"coordinates": [[139.76451, 35.68159],[139.75964, 35.68259]], "dates": ["2017-11-01T00:00:00Z", "2017-12-01T00:00:00Z"]}, {"coordinates": [[139.76451, 35.68159],[139.75964, 35.68259]], "dates": ["2017-12-01T00:00:00Z", "2018-01-01T00:00:00Z"]}, {"coordinates": [[139.76451, 35.68159],[139.75964, 35.68259]], "dates": ["2018-01-01T00:00:00Z", "2018-02-01T00:00:00Z"]}, {"coordinates": [[139.76451, 35.68159],[139.75964, 35.68259]], "dates": ["2018-02-01T00:00:00Z", "2018-03-01T00:00:00Z"]}, {"coordinates": [[139.76451, 35.68159],[139.75964, 35.68259]], "dates": ["2018-03-01T00:00:00Z", "2018-04-01T00:00:00Z"]}, {"coordinates": [[139.76451, 35.68159],[139.75964, 35.68259]], "dates": ["2018-04-01T00:00:00Z", "2018-05-01T00:00:00Z"]} ] features: list = [ { "type": "Feature", "geometry": { "type": "LineString", "coordinates": line["coordinates"], }, "properties": { "times": line["dates"], "style": { "weight": 10 }, }, } for line in lines ] pipelines: dict = { "type": "FeatureCollection", "features": features, } return pipelines def create_timeline_map(): m: folium.Map = folium.Map(location=[35.6815965, 139.7645151], zoom_start=16) pipelines: dict = create_geojson() TimestampedGeoJson( pipelines, add_last_point=False ).add_to(m) m.save('timeline_map-fixed.html') if __name__ == '__main__': create_timeline_map()
原理说明
- TimestampedGeoJson依赖Leaflet的时间轴插件,默认会将时间转换为浏览器本地时区处理,夏令时切换会导致日期计算出现偏移;使用UTC时间(带Z标记)可以跳过本地时区转换,确保时间基准统一。
- 当移除
period参数并设置add_last_point=False时,插件不会自动推算时间步进,而是直接收集所有Feature的times字段中的时间点,生成完全匹配预设日期的时间轴。
内容的提问来源于stack exchange,提问作者DADMODE1000
相关产品推荐
相关产品推荐

