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.
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)
There is no slot for the microseconds component in a time tuple:
>>> import time
>>> import datetime
>>> myDate = "2014-08-01 04:41:52,117"
>>> datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f").timetuple()
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=1, tm_hour=4, tm_min=41, tm_sec=52, tm_wday=4, tm_yday=213, tm_isdst=-1)
You'll have to add those manually:
>>> dt = datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f")
>>> time.mktime(dt.timetuple()) + (dt.microsecond / 1000000.0)
1406864512.117
The other method you could follow is to produce a timedelta() object relative to the epoch, then get the timestamp with the timedelta.total_seconds() method:
epoch = datetime.datetime.fromtimestamp(0)
(dt - epoch).total_seconds()
The use of a local time epoch is quite deliberate since you have a naive (not timezone-aware) datetime value. This method can be inaccurate based on the history of your local timezone however, see J.F. Sebastian's comment. You'd have to convert the naive datetime value to a timezone-aware datetime value first using your local timezone before subtracting a timezone-aware epoch.
As such, it is easier to stick to the timetuple() + microseconds approach.
Demo:
>>> dt = datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f")
>>> epoch = datetime.datetime.fromtimestamp(0)
>>> (dt - epoch).total_seconds()
1406864512.117
In Python 3.4 and later you can use
timestamp = datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f").timestamp()
This doesn't require importing the time module. It also uses less steps so it should be faster. For older versions of python the other provided answers are probably your best option.
However, the resulting timestamp will interpret myDate in local time, rather than UTC, which may cause issues if myDate was given in UTC
Your input time is in UTC; it is incorrect to use time.mktime() here unless your local timezone is always UTC.
There are two steps:
Convert the input rfc 3339 time string into a datetime object that represents time in UTC
from datetime import datetime utc_time = datetime.strptime("2015-09-15T17:13:29.380Z", "%Y-%m-%dT%H:%M:%S.%fZ")You've already done it. See also Convert an RFC 3339 time to a standard Python timestamp
Convert UTC time to POSIX time expressed in milliseconds:
from datetime import datetime, timedelta milliseconds = (utc_time - datetime(1970, 1, 1)) // timedelta(milliseconds=1) # -> 1442337209380For a version that works on Python 2.6-3+, see How can I convert a datetime object to milliseconds since epoch (unix time) in Python?
Unfortunately, there is no miliseconds in timetuple. However, you don't need timetuple. For timestamp, just call
datetime.strptime(...).timestamp()
As for timezone, check out tzinfo argument of datetime.
EDIT: tzinfo
>>> d
datetime.datetime(2015, 9, 15, 17, 13, 29, 380000)
>>> d.timestamp()
1442330009.38
>>> import pytz
>>> d.replace(tzinfo=pytz.timezone("US/Eastern")).timestamp()
1442355209.38
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"
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'
>>> import time
>>> import datetime
>>> s = "01/12/2011"
>>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
1322697600.0
I use ciso8601, which is 62x faster than datetime's strptime.
t = "01/12/2011"
ts = ciso8601.parse_datetime(t)
# to get time in seconds:
time.mktime(ts.timetuple())
You can learn more here.
[Edited following suggestion in the comments]
Using Ben Alpert's answer to How can I convert a datetime object to milliseconds since epoch (unix time) in Python we can do the following:
from datetime import datetime
def unix_time(dt):
epoch = datetime.utcfromtimestamp(0)
delta = dt - epoch
return delta.total_seconds()
def unix_time_millis(dt):
return int(unix_time(dt) * 1000)
a = datetime.strptime("2015-06-27T02:10:05.653000Z", "%Y-%m-%dT%H:%M:%S.%fZ")
unix_time_millis(a)
returns:
1435371005653
which is equivalent to: Sat, 27 Jun 2015 02:10:05 GMT (as expected)
We can also use datetime's .strftime('%s') to get unix time, even milliseconds using the following (but this is not advised):
from decimal import Decimal
int(Decimal(datetime.strptime("2015-06-27T02:10:05.653000Z", "%Y-%m-%dT%H:%M:%S.%fZ").strftime('%s.%f'))*1000)
returns:
1435396205653
equivalent to: Sat, 27 Jun 2015 09:10:05 GMT (on my mac in San Diego; Note: this is 7 hours off what we may have expected).
The cause of the error is described by J.F. Sebastian in the comments of the link above and in this answer regarding .strftime('%s') behavior. J.F. Sebastian points out that "it is not supported, it is not portable, it may silently produce a wrong result for an aware datetime object, it fails if input is in UTC (as in the question) but local timezone is not UTC"
There are two parts:
to convert
"2015-06-27T02:10:05.653000Z"into a datetime object, see How to parse ISO formatted date in Python?import re from datetime import datetime utc_time = datetime(*map(int, re.findall(r'\d+', time_string))to convert the UTC time to POSIX timestamp as integer milliseconds, see How can I convert a datetime object to milliseconds since epoch (unix time) in Python?
from datetime import datetime def timestamp_millis(utc_time, epoch=datetime(1970, 1, 1)): td = utc_time - epoch return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) // 10**3