0

I have a timestamp like this: 2021-01-03T01:59:00Z. How can I write a subtraction to get the timestamp a day earlier than the one indicated in ISO 8601 format?

Thanks!

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
luca canonico
  • 27
  • 1
  • 8
  • I think this might be closed as a combination-dupe of e.g. [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/q/127803/10197418) and [Generate RFC 3339 timestamp in Python](https://stackoverflow.com/q/8556398/10197418) (of which the latter again is closed as dupe although RFC3339 is only a subset of ISO8601) – FObersteiner Nov 18 '21 at 14:43

1 Answers1

0

You can use delta for take away 1 day

your_timestamp = '2021-01-03T01:59:00Z'
result = datetime.datetime.strptime(your_timestamp, "%Y-%m-%dT%H:%M:%S%z") - datetime.timedelta(days=1)
Maksym Sivash
  • 63
  • 1
  • 6
  • 1
    Simpler and more efficient [datetime.fromisoformat](https://stackoverflow.com/a/62769371/10197418). And I think the OP wants output in ISOformat string as well (so just reverse the oparation by `datetimeobject.isoformat` method or `strftime`). – FObersteiner Nov 18 '21 at 13:59
  • Hi, I try it but I have this error AttributeError: type object 'datetime.datetime' has no attribute 'datetime' – luca canonico Nov 18 '21 at 14:02
  • @lucacanonico: use `import datetime` and not `from datetime import datetime`. The latter import just one class, but we need also `timedelta`. It just make you some more typing, but less confusing (IMO) – Giacomo Catenazzi Nov 18 '21 at 14:05
  • @MrFuppes i checked it. in my variant it take 6.47 µs ± 72.3 ns per loop if i use your variant, it's takes 196 ns ± 0.563 ns per loop. So your variant more faster – Maksym Sivash Nov 18 '21 at 14:07
  • @MaksymSivash well, faster is sometimes less pretty (as in this case...), so `strptime` is fine if OP has to do this operation like once in a while. But I think you should add the output to ISO-format to your answer as well. – FObersteiner Nov 18 '21 at 14:09
  • @MrFuppes yes I would like to get the timestamp in ISOformat string; Maksym Sivah method is usefull but don't answer my question – luca canonico Nov 18 '21 at 14:31
  • @lucacanonico e.g. `result.isoformat(timespec='seconds').replace('+00:00', 'Z')` should work – FObersteiner Nov 18 '21 at 14:38