在 python 中向时间戳添加秒数

Adding seconds to timestamp in python

我有很多 timestamp 个字符串,例如这个 2017-04-18 05:03:40.966084,脚本需要向 timestamp 添加秒数。我一直在尝试将字符串转换为合法的 timestamp 对象,然后使用 timedelta 添加秒数,但由于某种原因它不起作用。

这是我目前拥有的:

duration = "150.100"
timestamp = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S.%f")
timestamp_e = timestamp+timedelta(seconds=duration)

我的做法正确吗?

timedelta 是调整时间戳的好方法。但是请注意,您的 duration 变量是一个字符串。根据 documentation 它应该是整数或浮点数:

All arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative.