简体   繁体   中英

Date format conversion works on windows but gives an error in Linux

I am trying to format date to a specific format. The code deploys successfully on Windows with Python 3.7. however, it doesn't work on Linux Debian 9.11 - Oython 3.5. Cannot figure out the solution. Any help is really appreciated.

def parse_date(date_string: str, date_format: str) -> str:
    """
    '2019-04-12T00:00:00.000-07:00' --> "%Y-%m-%dT%H:%M:%S.%f%z"
    '2019-04-28T07:25:39.668Z' --> "%Y-%m-%dT%H:%M:%S.%fZ"
    """
    req_date = dt.datetime.strptime(date_string, date_format)
    return req_date.strftime("%Y-%m-%d")

Works on windows

parse_date('2019-04-11T00:00:00.000-07:00', "%Y-%m-%dT%H:%M:%S.%f%z")

Fails on Linux

parse_date('2019-04-11T00:00:00.000-07:00', "%Y-%m-%dT%H:%M:%S.%f%z")

ValueError: time data '2019-04-11T00:00:00.000-07:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

expected return value: '2019-04-11'

I ended up using regex to solve overcome the problem and it works.

def parse_date_regex(date_string: str) -> str:
    """
    :return:
    """
    date = re.split('(\d{4}-\d{2}-\d{2})', date_string)
    return [res for res in date if len(res) == 10][0]

In Python 3.5, you could not have a colon in your UTC offset.

UTC offset in the form +HHMM or -HHMM (empty string if the object is naive).

In Python 3.7 that changed to allow the colon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM