Home > Software engineering >  Add seconds and microseconds to datetime if they are not set
Add seconds and microseconds to datetime if they are not set

Time:10-28

I have following datetime:

dt = datetime.datetime(2021, 10, 15, 0, 0, tzinfo=datetime.timezone.utc)

How can I add seconds and microsends to it with python code? So it has the same structure as:

datetime.datetime(2021, 10, 18, 15, 31, 21, 436248, tzinfo=datetime.timezone.utc)

CodePudding user response:

You can use timedelta for that. For example

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)

CodePudding user response:

I am not particularly sure what you want to do but you can do it like this with datetime, if you're trying to get the time this instant:

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)
  • Related