How to parse dates with -0400 timezone string in Python?

后端 未结 6 1365

I have a date string of the form \'2009/05/13 19:19:30 -0400\'. It seems that previous versions of Python may have supported a %z format tag in strptime for the trailing tim

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 10:01

    If you are on Linux, then you can use the external date command to dwim:

    import commands, datetime
    
    def parsedate(text):
      output=commands.getoutput('date -d "%s" +%%s' % text )
      try:
          stamp=eval(output)
      except:
          print output
          raise
      return datetime.datetime.frometimestamp(stamp)
    

    This is of course less portable than dateutil, but slightly more flexible, because date will also accept inputs like "yesterday" or "last year" :-)

提交回复
热议问题