iuuujkl
iuuujkl

Reputation: 2384

Add seconds and microseconds to datetime if they are not set

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)

Upvotes: 1

Views: 1325

Answers (1)

Anand Tripathi
Anand Tripathi

Reputation: 16126

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)

Upvotes: 3

Related Questions