Which is the correct or ideal or preferred method to convert a CST Date and/or Datetime field to UTC along with DST aware settings and store in MongoDB in ISO format in Python/PyMongo ? The source date/datetime field can come from any timezone (right now we know its CST), I need to convert all of them to UTC and store into target MongoDB.
As per MongoDB docs, MongoDB stores times in UTC by default, and will convert any local time representations into this form. Applications that must operate or report on some unmodified local time value may store the time zone alongside the UTC timestamp, and compute the original local time in their application logic.
Examples:
Method#1: with Timestamp (local timezone defined)
from datetime import datetime
import pytz
local_timezone = pytz.timezone("US/Central")
utc_datetime = local_timezone.localize(datetime.strptime ("1/2/2017 12:43 pm",'%m/%d/%Y %H:%M %p'),is_dst=True).astimezone(pytz.utc)
print(utc_datetime)
print(type(utc_datetime))
2017-01-02 18:43:00+00:00
<class 'datetime.datetime'>
without timestamp i.e. just date: - it adds an offset value of 6 hours in timestamp and during DST 5 hours. Removing or without astimezone(pytz.utc) , it returns date/time like 2017-01-02 00:00:00-06:00 i.e. showing -6 hours offset difference. Should we really be using astimezeon(pytz.utc) ??
from datetime import datetime
import pytz
local_timezone = pytz.timezone("US/Central")
utc_datetime = local_timezone.localize(datetime.strptime ("1/2/2017",'%m/%d/%Y'),is_dst=True).astimezone(pytz.utc)
print(utc_datetime)
print(type(utc_datetime))
2017-01-02 06:00:00+00:00
<class 'datetime.datetime'>
Method#2: with Timestamp (local timezone NOT defined)
from datetime import datetime, timezone
utc_datetime=datetime.utcfromtimestamp(datetime.strptime ("1/2/2017 12:43 pm",'%m/%d/%Y %H:%M %p').replace(tzinfo = timezone.utc).timestamp())
print(utc_datetime)
print(type(utc_datetime))
2017-01-02 12:43:00
<class 'datetime.datetime'>
without Timestamp i.e. just date part - no offset
from datetime import datetime, timezone
utc_datetime=datetime.utcfromtimestamp(datetime.strptime ("1/2/2017",'%m/%d/%Y').replace(tzinfo = timezone.utc).timestamp())
print(utc_datetime)
print(type(utc_datetime))
2017-01-02 00:00:00
<class 'datetime.datetime'>
After loading into MongoDB - it adds a "Z" at the end of the date/timestamp. Should I also add "tz_aware=True" when initiating connection with MongoClient ?
ISOFormat - changing above utc timestamp to isoformat() returns and gets loaded as string in MongoDB instead of a Date. So, how do we ensure it is still stored in ISO Date format in MongoDB ?
utc_datetime_iso=datetime.utcfromtimestamp(datetime.strptime ("1/2/2017",'%m/%d/%Y').replace(tzinfo = timezone.utc).timestamp()).**isoformat()**
print(utc_datetime_iso)
print(type(utc_datetime_iso))
2017-01-02T00:00:00
<class 'str'>