Search code examples
pythonpython-3.xpython-dateutil

How to convert date string by using Lib 'dateutil'?


When running dateutil.parser.parse("2017-09-19T04:31:43Z").strftime('%s') in Python, I obtain the following error:

ValueError: Invalid format string

What is the problem?


Solution

  • The same code works for me in Python 2.

    from dateutil.parser import parse
    print(parse("2017-09-19T04:31:43Z").strftime('%s'))
    # 1505813503
    

    or

    import dateutil.parser
    print(dateutil.parser.parse("2017-09-19T04:31:43Z").strftime('%s'))
    # 1505813503
    

    The OP claims that this does NOT work, giving the same ValueError: Invalid format string error.

    One explanation is that, according to this post, your option %s doesn't exist. See valid options of time.strftime here.

    Why did %s work on my system?

    Great answer by Darren Stone from this post

    In the Python source for datetime and time, the string STRFTIME_FORMAT_CODES tells us:

    "Other codes may be available on your platform.
    See documentation for the C library strftime function." 
    

    So now if we man strftime (on BSD systems such as Mac OS X), you'll find support for %s:

    %s is replaced by the number of seconds since the Epoch, UTC (see mktime(3))." 
    

    What can you do?

    It seems you want the Unix timestamp. As suggested by @jleahy here,

    If you want to convert a python datetime to seconds since epoch you should do it explicitly:

    datetime.datetime(2012,04,01,0,0).strftime('%s') # '1333234800'
    (datetime.datetime(2012,04,01,0,0) - 
     datetime.datetime(1970,1,1)).total_seconds() # 1333238400.0 
    

    In Python 3.3+ you can use timestamp() instead:

    datetime.datetime(2012,4,1,0,0).timestamp() # 1333234800.0