#๐Ÿ”’ convert hours to a datetime object

31 messages ยท Page 1 of 1 (latest)

brisk cape
#

hi, i have a question i want to convert hours to a datetime object like "%D;%H;%M. i tried something but it does not work any help

    def convert_duration(self, to_format):
        # hours are float like 399.634
        
        duration = timedelta(hours=self.duration_hours)
        formateerd = datetime.strftime(duration, to_format)
        return formateerd
latent mountainBOT
#

@brisk cape

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

steep plume
#

If it were me, I would get the current date time as now(), and then add the duration on to the current date time with + duration

slender dragon
#

I think it would be easier to just do the formatting manually

brisk cape
#

The duration_hours look like 1385.807

#

Or 399.643

copper pecan
#

but what would a datetime look like that corresponds to 399 hours?

brisk cape
copper pecan
#

A datetime is not a duration

brazen pasture
steep plume
brisk cape
#

Example what i got = input: 165.972 output: '06:21:58'

steep plume
#

hmm

brisk cape
#

Maybe if i do it manually with timedelta

copper pecan
#

6 days, 21 hours, 58 minutes?

brisk cape
#

I saw something like hours = duration.hours

brisk cape
steep plume
brisk cape
#

I will try

steep plume
#

!e

from datetime import timedelta

duration_timedelta = timedelta(hours=165.972)
days = duration_timedelta.days
seconds = duration_timedelta.seconds
    
print(f"{days=}, {seconds=}")
latent mountainBOT
steep plume
#

Then the rest is just math

slender dragon
#

I don't think you need the datetime module here at all

#

Just use // and %

copper pecan
#

good old divmod

snow pine
#

yall needa help me bro

#

im cooked

latent mountainBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.