Search code examples
pythondatetimepython-datetime

Convert Timestamp to ISO Format after Form Submission


Newbie question here and I'm not sure if this is best practice but:

I'm looking to convert a timestamp pulled in from a form submission and change it to ISO. For display reasons, I'd like to keep the time option displayed to the user like: Sept 30th 2017 11am EST. I'm looking to change this into 2017-09-30T11:00:00Z. I'm also trying to get this dynamic so if it is Oct 22nd 2017 10am EST it would result in 2017-10-22T10:00:00Z


Solution

  • You can use the (3rd party) dateutil module to help with parsing the incoming time value:

    from dateutil import parser
    
    ts = parser.parse('Sept 30th 2017 11am EST')
    print(ts.isoformat())
    
    print(parser.parse('Oct 22nd 2017 10am EST').isoformat())
    

    Output:

    2017-09-30T11:00:00
    2017-10-22T10:00:00
    

    This does lose the timezone, however, assuming EST is UTC-5:

    >>> print(parser.parse('Sept 30th 2017 11am EST', tzinfos={'EST': -(5*3600)}))
    2017-09-30 11:00:00-05:00
    >>> print(parser.parse('Oct 22nd 2017 10am EST', tzinfos={'EST': -(5*3600)}))
    2017-10-22 10:00:00-05:00