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.
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'
The simplest way would be to use slicing to just chop off the last three digits of the microseconds:
def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
return s[:-3]
I strongly recommend just chopping. I once wrote some logging code that rounded the timestamps rather than chopping, and I found it actually kind of confusing when the rounding changed the last digit. There was timed code that stopped running at a certain timestamp yet there were log events with that timestamp due to the rounding. Simpler and more predictable to just chop.
If you want to actually round the number rather than just chopping, it's a little more work but not horrible:
def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
head = s[:-7] # everything up to the '.'
tail = s[-7:] # the '.' and the 6 digits after it
f = float(tail)
temp = "{:.03f}".format(f) # for Python 2.x: temp = "%.3f" % f
new_tail = temp[1:] # temp[0] is always '0'; get rid of it
return head + new_tail
Obviously you can simplify the above with fewer variables; I just wanted it to be very easy to follow.
As of Python 3.6 the language has this feature built in:
def format_time():
t = datetime.datetime.now()
s = t.isoformat(timespec='milliseconds')
return s
According to the documentation of datetime.strptime() https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior, technical note (4), %f accepts only 1 - 6 chars:
%f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available). When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right.
I do NOT believe you have solved the problem correctly. You should not prefix the string with zero, but instead drop everything past 6 (which is less significant to contributing to time).
Something like this:
s='2014-11-19 00:00:00.0000000'
print (datetime.datetime.strptime((s[:26]).strip(), '%Y-%m-%d %H:%M:%S.%f')).date()
If you only want the date, only extract the date!
>>> datetime_string = '2014-11-19 00:00:00.0000000'
>>> date_string = datetime_string[:10]
>>> date_string
'2014-11-19'
>>> print(datetime.strptime(date_string, '%Y-%m-%d')).date()
2014-11-19
Using dparser:
import dateutil.parser as dparser
dt_1 = '2019-02-16T10:41:20.6080000+01:00'
print("Datetime: {}".format(dparser.parse(dt_1,fuzzy=True)))
OUTPUT:
Datetime: 2019-02-16 10:41:20.608000+01:00
If you want the date component:
print("Date: {}".format(dparser.parse(dt_1,fuzzy=True).date()))
OUTPUT:
Date: 2019-02-16
Looks like you can use simple string slicing.
Ex:
import datetime
timestamp = "2019-02-16T10:41:20.6080000+01:00"
parsed_timestamp = datetime.datetime.strptime(timestamp[:26], "%Y-%m-%dT%H:%M:%S.%f").date()
print(parsed_timestamp)
Output:
2019-02-16
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)
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"