函数式编程
假设变量中my_time_1存储的时间与X_var您希望的时间有一定的小时差。您可以通过执行以下操作“手动”取消增量:X_var = -4 # In your case the delta is equal to -4from datetime import timedelta my_time_1 = my_time_1 + timedelta(hours=X_var)但是,这不是很干净,也许您应该将根据前一个时区表示的时间转换为根据后一个时区表示的时间。您可以使用这个自定义函数:# I copied it from some SO question but can't find which oneimport pytz, datetime def convert_datetime_timezone(date_and_time_input, tz1, tz2): tz1 = pytz.timezone(tz1) tz2 = pytz.timezone(tz2) dt = datetime.datetime.strptime(date_and_time_input,"%Y-%m-%d %H:%M:%S") dt = tz1.localize(dt) dt = dt.astimezone(tz2) dt = dt.strftime("%Y-%m-%d %H:%M:%S") return dt因此,要从my_time_1America/New_York 切换回 UTC,您可以使用:my_time_1 = convert_datetime_timezone(my_time_1, America/New_York, UTC)您应该采取什么措施来解决您的问题:代替:new_event.start = datetime.strptime(str(obj.start_date) ,"%Y-%m-%d %H:%M:%S") new_event.end = datetime.strptime(str(obj.end_date) ,"%Y-%m-%d %H:%M:%S")和:import pytz, datetime def convert_datetime_timezone(date_and_time_input, tz1, tz2): tz1 = pytz.timezone(tz1) tz2 = pytz.timezone(tz2) dt = datetime.datetime.strptime(date_and_time_input,"%Y-%m-%d %H:%M:%S") dt = tz1.localize(dt) dt = dt.astimezone(tz2) dt = dt.strftime("%Y-%m-%d %H:%M:%S") return dtadjusted_start_date = convert_datetime_timezone(obj.start_date, America/New_York, UTC)adjusted_end_date = convert_datetime_timezone(obj.end_date, America/New_York, UTC)new_event.start = datetime.strptime(str(adjusted_start_date) ,"%Y-%m-%d %H:%M:%S") new_event.end = datetime.strptime(str(adjusted_end_date) ,"%Y-%m-%d %H:%M:%S")