如果未设置,则将秒和微秒添加到日期时间
Add seconds and microseconds to datetime if they are not set
我有以下日期时间:
dt = datetime.datetime(2021, 10, 15, 0, 0, tzinfo=datetime.timezone.utc)
如何使用 python 代码为其添加秒和微秒?所以它具有与以下相同的结构:
datetime.datetime(2021, 10, 18, 15, 31, 21, 436248, tzinfo=datetime.timezone.utc)
您可以为此使用 timedelta。例如
from datetime import timedelta
dt = datetime.datetime(2021, 10, 15, 0, 0, tzinfo=datetime.timezone.utc)
if not dt.second:
dt = dt + timedelta(seconds=21)
if not dt.microsecond:
dt = dt + timedelta(microseconds=23)
我不是特别确定你想做什么,但你可以像这样用 datetime 来做,如果你想立即获得时间:
from datetime import datetime
#get seconds/microseconds
now = datetime.now()
seconds = int(now.strftime("%S"))
microseconds = int(now.strftime("%f"))
datetime.datetime(2021, 10, 15, 31, seconds, microseconds, tzinfo=datetime.timezone.utc)
我有以下日期时间:
dt = datetime.datetime(2021, 10, 15, 0, 0, tzinfo=datetime.timezone.utc)
如何使用 python 代码为其添加秒和微秒?所以它具有与以下相同的结构:
datetime.datetime(2021, 10, 18, 15, 31, 21, 436248, tzinfo=datetime.timezone.utc)
您可以为此使用 timedelta。例如
from datetime import timedelta
dt = datetime.datetime(2021, 10, 15, 0, 0, tzinfo=datetime.timezone.utc)
if not dt.second:
dt = dt + timedelta(seconds=21)
if not dt.microsecond:
dt = dt + timedelta(microseconds=23)
我不是特别确定你想做什么,但你可以像这样用 datetime 来做,如果你想立即获得时间:
from datetime import datetime
#get seconds/microseconds
now = datetime.now()
seconds = int(now.strftime("%S"))
microseconds = int(now.strftime("%f"))
datetime.datetime(2021, 10, 15, 31, seconds, microseconds, tzinfo=datetime.timezone.utc)