0

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()
bfmcneill
  • 125
  • 13

1 Answers1

0

It's generally a good idea to leave the database field in its most agnostic format.

Create a method to handle the conversion details.

If you're annoyed by the prospect of typing out the full date/time conversion every time you need to have a date output, you could create a method in your object which handles the conversion in the way you like.

That way, you can name it something easy to remember and save yourself the hassle of remembering the exact notation of the date / time format function.

You might even create a super-class for your objects, and add the method there, so that it would be inherited by all the objects which you'd like to have this behavior available.

So if you have BlogObject class as a super-class, and BlogPost inherits from BlogObject, and you're accessing a standard field which exists in all those objects, such as Date Created or Date Modified

class BlogObject(BaseClassName):
    def pretty_create_dt():
        self.beatify_date(self.update_dt)

    def beautify_date(date):
        #[your format code]

#then have the other class(es) inherit the method:

class BlogPost(BlogObject):
    def get_xmas_date_before(days_before_xmas):
        date_x_before_christmas = self.beautify_date(self.xmas_dt - days_before_xmas)
        #pseudo-code-ish, just to get the point across

That way, when you call a function from your template, it's already formatted by the Model or Controller. You should avoid doing this sort of thing in the View, because it's bad MVC practice, especially for something you plan to utilize application-wide.

The reason that this is the generally-accepted pattern is that

  1. it reduces repetitive code processing which is prone to human error

  2. it is less work-intensive for future development

  3. It maintains the "separation on duty" inherent in MVC framework

    For example, if date format policy were to change, perhaps due to internationalization, then you'd want a solution which could be modified in one location (Model or Controller super-class), rather than in 1,000 view instances

Community
  • 1
  • 1
w36.site
  • 16
  • 4