0

If I have a datetime.timedelta of: datetime.timedelta(0, 0, 66)

print my_dt 0:00:00.000066

How can I keep and print just the seconds and the microseconds together? (i.e. strip the mins and hours).

I can see how to take just the micro and or the seconds, i.e. by those objects (e.g. my_dt.microseconds) - but I would like to keep both in the same cmd without any ugly formatting, sticking strings together after the fact.

For this example the output I am after would be:

00.000066

Any help appreciated (python n00b)

Version:

  • Python 2.6.6
maxhb
  • 8,554
  • 9
  • 29
  • 53
mbbxedh2
  • 137
  • 1
  • 2
  • 11
  • Sorry -0 yiou want to format the output without using formatting strings? Can you clarify on that? – jsbueno Mar 07 '16 at 16:41
  • Also, why are y9u using Python2.6 that is quite an old version (no, it is not the "second to last", the newest version is 3.5, and 2.6 is 6 versions behind that - it is ok to use 2.7 if you have thngs that need Python 2, but you really should not) – jsbueno Mar 07 '16 at 16:43

1 Answers1

2

Here is the official documentation for datetime util.

datetime

If you have a timedelta objects, it means that you've have a time interval which is stable. timedelta object has 3 attributes: days, seconds and microseconds.

For example: If your time interval is 1 day, 5 hours, 23 minutes, 10 seconds and 50 microseconds; do you want the output format to be only 10.000050 ? I'm guessing like the above.

So your code should be like:

seconds = my_dt.seconds%60
microseconds = my_dt.microseconds%1000000
result = "%d.%d" %(seconds,microseconds)
Cagatay Barin
  • 3,428
  • 2
  • 24
  • 43
  • you really sshouldues the string interpolation with the `.format` string method - or the `%` string operator, isntead of concatenating strings like this. – jsbueno Mar 07 '16 at 16:44
  • That's another way but would this be a problem ? I use also like this and haven't encountered any problem until now. – Cagatay Barin Mar 07 '16 at 16:46
  • Ok I fixed the format but I'm just wondering would it be a problem to cast an integer to a string? If so, I've used this method couple of times in my project. I might think of changing them. – Cagatay Barin Mar 07 '16 at 16:53
  • No - the string formatting "%d" takes care of the needed conversions. That is the idea behind a very-high-level language: this i sn ot casting, the "%d" formatting expects a numeric value. – jsbueno Mar 07 '16 at 17:30
  • Thank you for your advice. I worked with java a lot and still learning python. I'll do like this next time. – Cagatay Barin Mar 07 '16 at 17:34