I recently added in my settings.py USE_TZ = True to get Celery working on my Django project and now in my other views that use the datetime.strptime command, it is adding the -04:00 since my time zone is America/New_York. I don't need the time zone for this field. How do I remove the timezone from this? Here is my code below.
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")
Let's suppose in the variable my_time_1 is stored the time with a delta of X_var hours with respect to the one you wish.
You can cancel the delta "manually" by doing this:
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)
However, this is not very clean, and maybe you should convert a time expressed according to a former timezone into a time expressed according to a latter one.
You could use this custom function:
# 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
And so, to switch back my_time_1 from America/New_York to UTC, you can use:
my_time_1 = convert_datetime_timezone(my_time_1, America/New_York, UTC)
What you should do to fix your problem:
substitute:
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")
with:
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With