38
>>> a = str(datetime.now())
>>> a
'2012-03-22 11:16:11.343000'

I need to get a string like that: '16:11.34'.

Should be as compact as possible.

Or should I use time() instead? How do I get it?

4
  • You mean you want it truncated as 16:11.34, or something else? Mar 22, 2012 at 18:29
  • Yes, trancate or foramt or parse. I don't know.
    – Prostak
    Mar 22, 2012 at 18:30
  • 1
    @Marcin, I haven't tried anythong because I don't know what to try.
    – Prostak
    Mar 22, 2012 at 18:32
  • Maybe it should read whathaveyouresearched ...
    – hochl
    Mar 22, 2012 at 22:27

8 Answers 8

58

What about:

datetime.now().strftime('%M:%S.%f')[:-4]

I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.

EDIT

If the %f modifier doesn't work for you, you can try something like:

now=datetime.now()
string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]

Again, I'm assuming you just want to truncate the precision.

9
  • '>>>datetime.now().strftime('%M:%S.%f')[:-4]' Result: '' Something is not correct.
    – Prostak
    Mar 22, 2012 at 18:36
  • [:-4] means "start at the beginning and exclude the last 4 characters". For some reason, %f isn't working here and my final result is 36:31.f truncated to 36:. @Prostak may also be getting a truncated result...
    – Izkata
    Mar 22, 2012 at 18:41
  • 2
    What is incorrect? Does it raise an error? I think the %f modifier was added in python 2.6 (although I'm not positive) -- what version of python are you using?
    – mgilson
    Mar 22, 2012 at 18:42
  • I am restricted to 2.4.3. When I am using datetime.now().strftime('%M:%S.%f')[:-4] I get ''. If I use datetime.now().strftime('%M:%S.f')[:-4], I get '46:'
    – Prostak
    Mar 22, 2012 at 18:47
  • Ahhh...I've added a solution that should work with older versions as well.
    – mgilson
    Mar 22, 2012 at 18:50
17

This solution is very similar to that provided by @gdw2 , only that the string formatting is correctly done to match what you asked for - "Should be as compact as possible"

>>> import datetime
>>> a = datetime.datetime.now()
>>> "%s:%s.%s" % (a.minute, a.second, str(a.microsecond)[:2])
'31:45.57'
4
  • what about method strftime() .... I just can't figure out the parameter for milliseconds datetime.now().strftime('%M:%S.??'). maybe you know?
    – Prostak
    Mar 22, 2012 at 23:40
  • If you HAVE to use strftime then the solution from @mgilson seems like what you'd need to do, that is: datetime.datetime.now().strftime("%M:%S.%f")[:-4] to get the exact format that you asked for >>>import datetime >>>datetime.datetime.now().strftime("%M:%S.%f")[:-4] '14:07.90'
    – Pythomania
    Mar 23, 2012 at 16:17
  • but i don't have to use strftime()......... it is just the one that provides one line solution
    – Prostak
    Mar 23, 2012 at 18:46
  • 1
    In that case, if you don't mind the three different function calls to datetime.now(), you could do >>> "%s:%s.%s" % (datetime.datetime.now().minute, datetime.datetime.now().second, str(datetime.datetime.now().microsecond)[:2]) '21:51.16' This does make calling datetime.now() redundant but I don't think there is a time difference in the three different function calls. Please correct me if I am wrong.
    – Pythomania
    Mar 23, 2012 at 19:23
4

if you want your datetime.now() precise till the minute , you can use

datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M'), '%Y-%m-%d %H:%M')

similarly for hour it will be

datetime.strptime(datetime.now().strftime('%Y-%m-%d %H'), '%Y-%m-%d %H')

It is kind of a hack, if someone has a better solution, I am all ears

3

Another similar solution:

>>> a=datetime.now()
>>> "%s:%s.%s" % (a.hour, a.minute, a.microsecond)
'14:28.971209'

Yes, I know I didn't get the string formatting perfect.

2
  • what about method strftime() .... I just can't figure out the parameter for milliseconds datetime.now().strftime('%M:%S.??'). maybe you know?
    – Prostak
    Mar 22, 2012 at 23:40
  • I would use %d instead of %s because you are dealing with integer values (digits). Apr 13, 2015 at 0:17
3
import datetime from datetime

now = datetime.now()

print "%0.2d:%0.2d:%0.2d" % (now.hour, now.minute, now.second)

You can do the same with day & month etc.

0

time.second helps a lot put that at the top of your python.

0

To the min, seconds and milliseconds, you can first import datetime. Then you define a object with the datetime.datetime.now(). Then you can as that object for min, seconds and milliseconds, bu using the sub function of the class.

import datetime
now = datetime.datetime.now()
print (now.year)
print (now.month)
print (now.day)
print (now.hour)
print (now.minute)
print (now.second)
print (now.microsecond)

You can read more about her https://docs.python.org/3/library/datetime.html#datetime.datetime.year

-2

Sorry to open an old thread but I'm posting just in case it helps someone. This seems to be the easiest way to do this in Python 3.

from datetime import datetime

Date = str(datetime.now())[:10]
Hour = str(datetime.now())[11:13]
Minute = str(datetime.now())[14:16]
Second = str(datetime.now())[17:19]
Millisecond = str(datetime.now())[20:]

If you need the values as a number just cast them as an int e.g

Hour = int(str(datetime.now())[11:13])
1
  • 1
    This not a good idea. You're not using the methods that the library offers - see other answers. If they ever change the format so that the spaces are shifted, you'll end up with with hardcoded string positions burried somewhere deep in your code which at best will raise an error, at worst will render computations incorrect and potentially hard to debug. Never hardcode positions like that if you can avoid it, which you can here. Jan 30, 2020 at 0:12

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.