Python实现UTC转EST时区 处理Jira获取日期适配GTM接口需求
实现步骤
1. 环境依赖安装
先安装需要的第三方包:
pip install python-dateutil google-api-python-client pytz # Python 3.9+可不用安装pytz,用自带zoneinfo
2. 日期转换逻辑
注意:使用America/New_York时区标识符,自动适配夏令时/冬令时,不要硬编码EST偏移量,避免时间错误
from datetime import datetime, time from dateutil import parser import pytz # Python 3.9+ 可替换为 from zoneinfo import ZoneInfo # 定义EST时区 est_tz = pytz.timezone("America/New_York") # Python 3.9+写法:est_tz = ZoneInfo("America/New_York") # Jira返回的示例数据 jira_start_str = "2021-09-20T07:16:08.000+0000" jira_end_str = "2021-09-21" # 处理开始日期:转EST时区后设置为当天00:00:00 start_datetime_utc = parser.isoparse(jira_start_str) start_datetime_est = start_datetime_utc.astimezone(est_tz) # 重置时间为00:00:00 start_datetime_est_final = datetime.combine(start_datetime_est.date(), time.min, tzinfo=est_tz) # 处理结束日期:直接作为EST日期,设置为当天23:59:59 end_date = datetime.strptime(jira_end_str, "%Y-%m-%d").date() end_datetime_est_final = datetime.combine(end_date, time.max, tzinfo=est_tz) # 可选:转为GTM常用的Unix时间戳(秒级) start_timestamp = int(start_datetime_est_final.timestamp()) end_timestamp = int(end_datetime_est_final.timestamp()) # 可选:转为指定格式字符串 print(start_datetime_est_final.strftime("%Y-%m-%d %H:%M:%S %Z%z")) print(end_datetime_est_final.strftime("%Y-%m-%d %H:%M:%S %Z%z"))
3. 调用GTM API创建标签
前置操作:
- Google Cloud Console启用Tag Manager API
- 生成服务账号JSON密钥,将服务账号邮箱添加到对应GTM容器的编辑权限中
- 替换代码中的
account_id、container_id、workspace_id为你自己的GTM参数
from googleapiclient.discovery import build from google.oauth2 import service_account # 认证初始化 SCOPES = ['https://www.googleapis.com/auth/tagmanager.edit.containers'] SERVICE_ACCOUNT_FILE = '你的服务账号密钥文件路径.json' credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) gtm_service = build('tagmanager', 'v2', credentials=credentials) # 替换为自己的GTM参数 account_id = '你的GTM账户ID' container_id = '你的GTM容器ID' workspace_id = '你的工作区ID' parent_path = f'accounts/{account_id}/containers/{container_id}/workspaces/{workspace_id}' # 示例:创建自定义HTML标签,将处理好的日期作为变量传入 tag = { "name": "自定义日期标签", "type": "html", "parameter": [ { "type": "template", "key": "html", "value": f"<script>window.START_DATE_EST = {start_timestamp}; window.END_DATE_EST = {end_timestamp};</script>" }, { "type": "boolean", "key": "supportDocumentWrite", "value": False } ], "firingTriggerId": ["2147479553"] # 替换为你自己的触发条件ID,示例为All Pages触发器 } # 调用API创建标签 response = gtm_service.accounts().containers().workspaces().tags().create( parent=parent_path, body=tag ).execute() print("标签创建成功,ID为:", response["tagId"])
内容的提问来源于stack exchange,提问作者Beginner
相关产品推荐
相关产品推荐

