datetime - Python 3.4: how to add zero milliseconds and change their formatting -


i need format datetime displayed in following way: "2014-06-04 12:05:10.000", "2014-06-04 12:05:10.250", "2014-06-04 12:05:10.500", "2014-06-04 12:05:10.750".

my current datetime "2010-01-01 12:05:10.250000", , it's sum of initial datetime , incrementing timedelta:

delta = datetime.timedelta(hours=0, minutes=0, seconds=0, milliseconds=250) time = (date_initial + delta) 

here 2 questions:

1). how add "000" when there no milliseconds (i mean adding whole seconds), otherwise face "index out of list" error when trying smth milliseconds part

datetime_split = str(time).split('.')     date_2 = datetime_split[1] 

is there shorter , cleverer way add ".000" milliseconds other loop "split -- if there right of "." -- if no, add ".000". additional problem here string format instead of datetime.

2). how change milliseconds formatting ".250000" ".250". again, after manual adding of ".000" it'd little harder divide 1000, because zeros disturb.

thanks in advance. tried find working answer didn't succeed.

upd: tried ".rstrip('0')" remove zeros, beside others tried

dt.datetime.strptime(str(date), "%y-%m-%d %h:%m:%s").strftime(str(date_bid),"%y") 

but did not work me.

does want achieve?

def formatdt(dt):     return dt.strftime('%y-%m-%d %h:%m:%s.')+(            "%0.3f"%(dt.microsecond/10**6))[2:] 

outputs:

>>> formatdt(datetime.datetime(2014, 4, 1)) '2014-04-01 00:00:00.000' >>> formatdt(datetime.datetime.now()) '2014-11-27 14:40:27.968' 

Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -