Python3.7 :: Eve:
Looking for a way to format datetime for a domain field instead of setting a global datetime format?
I am trying to store yyyy-mm-dd
format but I don't want to change how the _created
and _update
work. Am I better off just storing the string and handling date conversion as part of the front end render?
--edit-- Would it be expensive to use a validator like so?
import datetime
from dateutil.parser import parse
from eve.io.mongo import Validator
class MyValidator(Validator):
"""
Extend / override the built-in validation rules
"""
def _validate_is_yyyymmdd(self, is_yyyymmdd, field, value):
"""datetime format yyyy-mm-dd"""
print(is_yyyymmdd, field, value)
print(datetime.datetime.strptime(value, r'%Y-%m-%d'))
print(is_yyyymmdd and datetime.datetime.strptime(value, r'%Y-%m-%d'))
try:
if is_yyyymmdd and datetime.datetime.strptime(value, r'%Y-%m-%d'):
return
except:
self._error(field, "Value is not valid yyyy-mm-dd")
volumes.py
volumes = {
'schema':{
'record_date':{
'type':'string',
'is_yyyymmdd':True,
},
'volume_gallons':{'type':'float'},
}
SOLVED - update
DATE_FORMAT = r"%Y-%m-%dT%H:%M:%S.%f%Z%z"
Using the new date format the payload can be submitted with a timezone adjustment which is then stored in mongo as UTC.
{
"record_date":"2019-04-06T15:49:12.012UTC+0500",
"group":"horizontal",
"program_year":2016
}
python script to help convert to utc from a given time
from datetime import datetime
from dateutil import tz
from dateutil.parser import parse
def main():
"""
modified solution found here: https://stackoverflow.com/questions/4770297/convert-utc-datetime-string-to-local-datetime
"""
# set the time zones to convert from and to
# https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
from_zone = tz.gettz('America/Denver')
to_zone = tz.tzutc()
# This is the format SQL Server outputs date time
datetime_str = "2019-03-21 02:37:21"
# local = datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
local = parse(datetime_str)
# Tell the datetime object that it's in local time zone since
# datetime objects are 'naive' by default
local = local.replace(tzinfo=from_zone)
# Convert time zone
utc = local.astimezone(to_zone)
print(utc, local)
if __name__ == "__main__":
main()