0

I have a line of code here that works on my dev server for Django and Python using SQL Lite, however when I upload my code it gives me an error about my time zone . Here is my Code. Postgres doesn't like the %z at the end , however SQL Lite its fine. What do I do to fix this on my Heroku Postgres Production Environment? Thanks

new_event.start = datetime.strptime(str(obj.start_date) ,'%Y-%m-%d %H:%M:%S%z') 

Error Message: time data '2020-10-08 12:17:51-04:00' does not match format '%Y-%m-%d %H:%M:%S%z'

8
  • Python is having an issue with the '-04:00` and %z as it has a colon in it. This has actually changed in Python 3.7: datetime.strptime('2020-10-08 12:17:51-04:00' ,'%Y-%m-%d %H:%M:%S%z') datetime.datetime(2020, 10, 8, 12, 17, 51,tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000))) Commented Oct 8, 2020 at 16:33
  • Why are you doing this anyway? You are taking a Python datetime and creating another datetime. Commented Oct 8, 2020 at 16:37
  • Im using the O365 package and it connects to office 365 via API, and im using it to post calendar events. So you have to have a start and end date . So what's my solution for this ? Commented Oct 8, 2020 at 16:41
  • 1
    Yeah, but the end result is you are have new_event.start = a datetime. So why not just: new_event.start=obj.start_date? It gets you the same result. Commented Oct 8, 2020 at 16:45
  • This is true, there was a reason why i did this. Im going to try it and see if it resolves it. Commented Oct 8, 2020 at 16:50

1 Answer 1

1

Assuming you have a good reason to get back where you started:

dt                                                                                                                                                                        
datetime.datetime(2020, 10, 8, 9, 33, 37, 216144, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-420, name=None))

datetime.strftime(dt, '%Y-%m-%d %H:%M:%S%z')                                                                                                                              
'2020-10-08 09:33:37-0700'

dt_2 = datetime.strptime(datetime.strftime(dt, '%Y-%m-%d %H:%M:%S%z'), '%Y-%m-%d %H:%M:%S%z') 

dt_2
datetime.datetime(2020, 10, 8, 9, 33, 37, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=61200)))

This makes the string returned from the datetime object be formatted with a time zone offset that does not have a colon. This means that strptime in Python < 3.7 can deal with it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.