I'm using dateString = date.strftime('%Y-%m-%d %H:%M:%S.%f')
on this date: 2012-06-28 16:11:17
which returns 2012-06-28 16:11:17.999771
which for some reason is unparseable by Objective-c. How can I limit the last part of the string to 3 decimal places rather than 6?
Asked
Active
Viewed 138 times
0

Snowman
- 31,411
- 46
- 180
- 303
-
date.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] – Aleksei astynax Pirogov Jun 28 '12 at 17:03
-
Nice, this worked! What does the [:-3] represent? (If you post as an answer, I can accept it) – Snowman Jun 28 '12 at 17:05
2 Answers
3
Use:
date.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
This is slicing (syntax [from : to(but but not include) : step]):
>>> '123456'[:-3]
'123'
>>> '123456'[3:]
'456'
>>> '123456'[1:-1]
'2345'
>>> '123456'[::2]
'135'
>>> '123456'[::-1]
'654321'
>>> '123456'[-2::]
'56'

Aleksei astynax Pirogov
- 2,483
- 15
- 19
-
Are there any catches with this though? Is it possible that my date returns less than 3 decimal places with my code above? If it did, then it would chop off more than I wanted.. – Snowman Jun 28 '12 at 17:17
-
2@mohabitar, `datetime(2012,6,28,0,0,0,0).strftime('%Y-%m-%d %H:%M:%S.%f')` -> `'2012-06-28 00:00:00.000000'` – Aleksei astynax Pirogov Jun 28 '12 at 17:19
0
[:-3]
method looses precision i.e., '17.999771'[:-3] -> '17.999'
but it should be 18.000
.
To correctly round the time you could convert datetime
object to seconds, round them and convert them back. e.g.:
from datetime import datetime
dt = datetime(2012, 6, 28, 16, 11, 17, 999771)
secs = (dt - datetime(1970, 1, 1)).total_seconds()
dt = datetime.utcfromtimestamp(round(secs, 3)) # round to thousands
print dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
# -> '2012-06-28 16:11:18.000'