There is the no directive mentioned in time.strftime(...) that will return you the milliseconds. Not sure from where you got the reference to use %f. In fact time.gmtime(...) holds the precision only upto seconds.
As a hack, in order to achieve this, you may explicitly format your string by preserving your milli second value as:
>>> import time
>>> time_in_ms = 1515694048121
>>> time.strftime('%Y-%m-%d %H:%M:%S:{}'.format(time_in_ms%1000), time.gmtime(time_in_ms/1000.0))
'2018-01-11 18:07:28:121'
Here's the list of valid directives:
+-----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
| Directive | Meaning | Notes |
+-----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
| %a | Locale’s abbreviated weekday name. | |
| %A | Locale’s full weekday name. | |
| %b | Locale’s abbreviated month name. | |
| %B | Locale’s full month name. | |
| %c | Locale’s appropriate date and time representation. | |
| %d | Day of the month as a decimal number [01,31]. | |
| %H | Hour (24-hour clock) as a decimal number [00,23]. | |
| %I | Hour (12-hour clock) as a decimal number [01,12]. | |
| %j | Day of the year as a decimal number [001,366]. | |
| %m | Month as a decimal number [01,12]. | |
| %M | Minute as a decimal number [00,59]. | |
| %p | Locale’s equivalent of either AM or PM. | (1) |
| %S | Second as a decimal number [00,61]. | (2) |
| %U | Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. | (3) |
| %w | Weekday as a decimal number [0(Sunday),6]. | |
| %W | Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. | (3) |
| %x | Locale’s appropriate date representation. | |
| %X | Locale’s appropriate time representation. | |
| %y | Year without century as a decimal number [00,99]. | |
| %Y | Year with century as a decimal number. | |
| %z | Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59]. | |
| %Z | Time zone name (no characters if no time zone exists). | |
| %% | | |
+-----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
Answer from Moinuddin Quadri on Stack OverflowVideos
There is the no directive mentioned in time.strftime(...) that will return you the milliseconds. Not sure from where you got the reference to use %f. In fact time.gmtime(...) holds the precision only upto seconds.
As a hack, in order to achieve this, you may explicitly format your string by preserving your milli second value as:
>>> import time
>>> time_in_ms = 1515694048121
>>> time.strftime('%Y-%m-%d %H:%M:%S:{}'.format(time_in_ms%1000), time.gmtime(time_in_ms/1000.0))
'2018-01-11 18:07:28:121'
Here's the list of valid directives:
+-----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
| Directive | Meaning | Notes |
+-----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
| %a | Locale’s abbreviated weekday name. | |
| %A | Locale’s full weekday name. | |
| %b | Locale’s abbreviated month name. | |
| %B | Locale’s full month name. | |
| %c | Locale’s appropriate date and time representation. | |
| %d | Day of the month as a decimal number [01,31]. | |
| %H | Hour (24-hour clock) as a decimal number [00,23]. | |
| %I | Hour (12-hour clock) as a decimal number [01,12]. | |
| %j | Day of the year as a decimal number [001,366]. | |
| %m | Month as a decimal number [01,12]. | |
| %M | Minute as a decimal number [00,59]. | |
| %p | Locale’s equivalent of either AM or PM. | (1) |
| %S | Second as a decimal number [00,61]. | (2) |
| %U | Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. | (3) |
| %w | Weekday as a decimal number [0(Sunday),6]. | |
| %W | Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. | (3) |
| %x | Locale’s appropriate date representation. | |
| %X | Locale’s appropriate time representation. | |
| %y | Year without century as a decimal number [00,99]. | |
| %Y | Year with century as a decimal number. | |
| %z | Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59]. | |
| %Z | Time zone name (no characters if no time zone exists). | |
| %% | | |
+-----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
You can easily use the datetime library to format microseconds using %f.
│ >>> from datetime import datetime
>>> datetime.utcnow().strftime("%Y%m%d-%H:%M:%S")
'20211018-16:02:38'
>>> datetime.utcnow().strftime("%Y%m%d-%H:%M:%S.%f")
'20211018-16:02:38.986417'
To get a date string with milliseconds, use [:-3] to trim the last three digits of %f (microseconds):
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'
Or shorter:
>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]
'2022-09-24 10:18:32.926'
See the Python docs for more "%" format codes and the strftime(3) man page for the full list.
With Python 3.6+, you can set isoformat's timespec:
>>> from datetime import datetime
>>> datetime.utcnow().isoformat(sep=' ', timespec='milliseconds')
'2019-05-10 09:08:53.155'
Python 2.6 added a new strftime/strptime macro %f. The docs are a bit misleading as they only mention microseconds, but %f actually parses any decimal fraction of seconds with up to 6 digits, meaning it also works for milliseconds or even centiseconds or deciseconds.
time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
However, time.struct_time doesn't actually store milliseconds/microseconds. You're better off using datetime, like this:
>>> from datetime import datetime
>>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
>>> a.microsecond
123000
As you can see, .123 is correctly interpreted as 123 000 microseconds.
I know this is an older question but I'm still using Python 2.4.3 and I needed to find a better way of converting the string of data to a datetime.
The solution if datetime doesn't support %f and without needing a try/except is:
(dt, mSecs) = row[5].strip().split(".")
dt = datetime.datetime(*time.strptime(dt, "%Y-%m-%d %H:%M:%S")[0:6])
mSeconds = datetime.timedelta(microseconds = int(mSecs))
fullDateTime = dt + mSeconds
This works for the input string "2010-10-06 09:42:52.266000"
You can use datetime's strftime() function to get this. The problem is that time's strftime() accepts a timetuple that does not carry microsecond information.
from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")
Should do the trick!
You are looking at the wrong documentation. The time module has different documentation.
You can use the datetime module strftime like this:
>>> from datetime import datetime
>>>
>>> now = datetime.now()
>>> now.strftime("%H:%M:%S.%f")
'12:19:40.948000'
In Python 3 this can be done in 2 steps:
- Convert timestring to
datetimeobject - Multiply the timestamp of the
datetimeobject by 1000 to convert it to milliseconds.
For example like this:
from datetime import datetime
dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
'%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000
print(millisec)
Output:
1482223122760.0
strptime accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime object. The format string (second argument) specifies the actual format of the string that you have passed.
Here is the explanation of the format specifiers from the official documentation:
%d- Day of the month as a zero-padded decimal number.%m- Month as a zero-padded decimal number.%Y- Year with century as a decimal number%H- Hour (24-hour clock) as a zero-padded decimal number.%M- Minute as a zero-padded decimal number.%S- Second as a zero-padded decimal number.%f- Microsecond as a decimal number, zero-padded to 6 digits.
For those who search for an answer without parsing and losing milliseconds,
given dt_obj is a datetime:
python3 only, elegant
int(dt_obj.timestamp() * 1000)
both python2 and python3 compatible:
import time
int(time.mktime(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000)