首页 > 解决方案 > ISO 格式的日期时间,毫秒到 000

问题描述

我的代码datetime.now(timezone.utc).astimezone(pytz.timezone("Europe/Berlin")).isoformat()打印以下格式'2020-03-17T16:54:53.559415+01:00'

但我希望毫秒为 0000 '2020-03-17T16:54:53.000+01:00'

我已经尝试过使用replace(miliseconds=0),但它从打印的字符串中完全删除了毫秒。

标签: pythondatetimedatetime-format

解决方案


您想.replace(microsecond=0)将毫秒(和微)秒归零。然后只需指定 ,timespecisoformat权利'milliseconds'

nowzeroed = datetime.now(timezone.utc).replace(microsecond=0)
nowberlin = nowzeroed.astimezone(pytz.timezone("Europe/Berlin"))
nowformatted = nowberlin.isoformat(timespec='milliseconds') 

推荐阅读