0

For a project, I'm fetching data from Salesforce and MongoDB and comparing field by field. The issue is the dates in MongoDB are stored in a string such as "Apr 15, 2016, 4:08:03 AM". The same field is stored in as DateTime datatype in Salesforce such as "2016-04-15T04:08:03.000+0000". I'm trying to convert either one of these fields to match with other format in python so I can compare them

So far, I have this

from datetime import datetime datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p') print(str(datetime_object)) #'2005-06-01 13:33:00' 
3
  • datetime.strptime already gives you a datetime instance. What's your question? Commented Apr 20, 2021 at 18:45
  • How do I convert "2016-04-15T04:08:03.000+0000" to "Apr 15, 2016, 4:08:03 AM". Or vice versa? Commented Apr 20, 2021 at 18:48
  • 2
    You don't need to convert to strings to compare. If the field has type datetime in the database, then unless you're doing something odd, you'll get a datetime instance when you do a query. You can compare datetime instances. Commented Apr 20, 2021 at 19:05

1 Answer 1

1

If you insist on comparing as strings...

from datetime import datetime a = "2016-04-15T04:08:03.000+0000" b = "Apr 15, 2016, 4:08:03 AM" a = datetime.strptime(a, '%Y-%m-%dT%H:%M:%S.%f%z') b = datetime.strptime(b, '%b %d, %Y, %I:%M:%S %p') b = b.replace(tzinfo=a.tzinfo) print(a.isoformat()) print(b.isoformat()) 
Sign up to request clarification or add additional context in comments.

3 Comments

Oops, I just noticed the time shift when I called .astimezone but you get the idea.
Thanks Justin. This was helpful.
Instead of astimezone, you can replace the tzinfo

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.