0

In python I am trying to parse the date string

Thu, 1 Oct 2015 16:05:43 +0200

to a struct_time trying

x = time.strptime(date_string, "%a, %d %b %Y %H:%M:%S +0000")

which yields a ValueError.

How to avoid the "+0200" (which I am not interested in)? Just remove the last 6 characters? Or is there a 'better' solution?

Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
Alex
  • 41,580
  • 88
  • 260
  • 469
  • I think you need `%z`. – TigerhawkT3 Oct 13 '15 at 07:44
  • The `%z` format string is available on `datetime.strptime` (not in `time.strptime`) and only from Python 3.2 on. For your specific case: you can use `datetime.strptime` + `%z` if you have a recent Python, and then convert it to a `struct_time` via the `datetime.timetuple()` method. But this simple instruction will introduce a dependence towards Python >= 3.2 that perhaps it's not justified by the simple task ... – FSp Oct 13 '15 at 07:54
  • 1
    use `posix_timestamp = mktime_tz(parsedata_tz("Thu, 1 Oct 2015 16:05:43 +0200"))` from `email.utils`. For pure stdlib Python 2/3 compatible code, see [Python: parsing date with timezone from an email](http://stackoverflow.com/a/23117071/4279) – jfs Oct 13 '15 at 09:18

1 Answers1

0

Just remove the last chunk; you can do that by slicing (removing the last 6 characters, yes), or by partitioning (splitting off the last section):

x = time.strptime(date_string.rpartition(' ')[0], "%a, %d %b %Y %H:%M:%S")

Partitioning should continue to work if the last chunk is not 6 characters (say, because you have dates with the timezone expressed as a 3-letter code).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Instead of partitioning, I'd recommend simply using the proper identifier of `%z` instead of `+0000`. – TigerhawkT3 Oct 13 '15 at 07:47
  • Hm ok, I thought I missed some 'special' argument mentioned on the documentation somewhere, but it does not seem to exist. Always trust Martijn... – Alex Oct 13 '15 at 07:47