Search code examples
pythondatetimetimedelta

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)

Solution

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