0

My problem is that I have an integer 366 (days) from 2000-01-01 and I need a date time object to of 2000-01-01 + 366 days. Not a string, a date time object.

I have a similar problem with microseconds needing to be in datetime.time. I have microseconds that's greater than the allowable range so datetime.time(microsecond=9999999999) will fail. What would be the most efficient way of solving for both of these?

2
  • This is unclear, you want to sum a date with a int that represents days ? Commented Jun 22, 2020 at 20:18
  • Ah sorry. I meant I'm given this large number (let's say the microseconds). I need to convert this number into hours, minutes, days, etc. so that it can be in a datetime.time object. Commented Jun 22, 2020 at 20:27

2 Answers 2

1
>>> import datetime
>>> datetime.timedelta(days=366)
datetime.timedelta(366)
>>> datetime.datetime(2000, 1, 1) + datetime.timedelta(days=366)
datetime.datetime(2001, 1, 1, 0, 0)
>>> 
>>> datetime.timedelta(microseconds=9999999999)
datetime.timedelta(0, 9999, 999999)  # 9999.999999 seconds
>>> datetime.datetime(2000, 1, 1) + datetime.timedelta(microseconds=9999999999)
datetime.datetime(2000, 1, 1, 2, 46, 39, 999999)
>>> str(datetime.timedelta(microseconds=9999999999))
'2:46:39.999999'  # 2 hours 46 minutes 39 seconds 

If you want a datetime.time object specifically, you can add it to any day for conversion, but beware this will fail for timeframes bigger than 24 hours:

>>> x = datetime.datetime(1,1,1) + datetime.timedelta(microseconds=9999999999)
>>> x
datetime.datetime(1, 1, 1, 2, 46, 39, 999999)
>>> x.time()
datetime.time(2, 46, 39, 999999)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. Sorry for the confusion, but the latter is different from the first problem. Focusing on the latter though, I only have microseconds. I only need a datetime.time object from it. How would I get that efficiently? Definitely got the first half correct though, using timedelta.
Are you sure you want a datetime.time from it? That represents a time of day, which can't go over 24 hours. I added a way to do it, but it might be simpler to divide by 60/60/24 yourself as there is no need for a library.
0

Use datetime() to create whatever date you wish, then add a timedelta to it.

from datetime import datetime, timedelta
d = datetime(year=2000, month=1, day=1) + timedelta(days=366)

1 Comment

I posted the top half because I couldn't figure out why some binary was coming out unsigned... and then realizing it wasn't. But this is the correct way to go about the first problem, i.e. the main problem of the post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.