CrazyCSGuy
CrazyCSGuy

Reputation: 143

Convert date (month, day, year, time) to Datetime format in python

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'

Upvotes: 0

Views: 891

Answers (1)

user5386938
user5386938

Reputation:

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())

Upvotes: 1

Related Questions