1 回答

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
假設(shè)變量中my_time_1存儲(chǔ)的時(shí)間與X_var您希望的時(shí)間有一定的小時(shí)差。
您可以通過(guò)執(zhí)行以下操作“手動(dòng)”取消增量:
X_var = -4 # In your case the delta is equal to -4
from datetime import timedelta
my_time_1 = my_time_1 + timedelta(hours=X_var)
但是,這不是很干凈,也許您應(yīng)該將根據(jù)前一個(gè)時(shí)區(qū)表示的時(shí)間轉(zhuǎn)換為根據(jù)后一個(gè)時(shí)區(qū)表示的時(shí)間。
您可以使用這個(gè)自定義函數(shù):
# I copied it from some SO question but can't find which one
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 dt
因此,要從my_time_1America/New_York 切換回 UTC,您可以使用:
my_time_1 = convert_datetime_timezone(my_time_1, America/New_York, UTC)
您應(yīng)該采取什么措施來(lái)解決您的問(wèn)題:
代替:
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 dt
adjusted_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")
添加回答
舉報(bào)