Convert string to epoch time? - python

I have a string in this format '2016-06-15T12:52:05.623Z'. I want to calculate the number of seconds of this time since epoch.
How can I do that?

In Python 3:
import dateutil.parser
t = dateutil.parser.parse("2016-06-15T12:52:05.623Z")
print(t.timestamp())

Use time to return the timestamp from datetime:
import datetime
import time
date = datetime.datetime.strptime('2016-06-15T12:52:05.623Z', "%Y-%m-%dT%H:%M:%S.%fZ")
print time.mktime(date.timetuple())
>> 1466005925.0

from datetime import datetime
my_date = '2016-06-15T12:52:05.623Z'
dtformat = '%Y-%m-%dT%H:%M:%S.%fZ'
d = datetime.strptime(my_date, dtformat)
epoch = datetime.utcfromtimestamp(0)
print (d - epoch).total_seconds()
# OUT: 1465995125.62

Related

python datetime with 6 digit milliseconds

How could I print 6 digit milli seconds in below format
>>> import datetime
>>> datetime.datetime.now(tz = datetime.datetime.now().astimezone().tzinfo).isoformat(timespec='milliseconds')
'2022-01-10T18:29:10.698000+05:30'
Actual Output:
'2022-01-10T18:29:10.108+05:30'
Expecting Output something like:
'2022-01-10T18:29:10.108000+05:30'
Use timespec=microseconds:
>>> dt = datetime.datetime.now(tz = datetime.datetime.now().astimezone().tzinfo).isoformat(timespec='microseconds')
'2022-01-10T14:05:55.742931+01:00'
Update:
If you want 0 for microsecond value, you can do:
now = datetime.datetime.now().astimezone()
now = now.replace(microsecond=now.microsecond // 1000 * 1000)
now = now.isoformat(timespec='microseconds')
print(now)
# Output
'2022-01-10T14:17:08.386000+01:00'
There are only 1000ms in 1 second, do you mean microseconds?
datetime.datetime.now(tz = datetime.datetime.now().astimezone().tzinfo).isoformat(timespec='microseconds')
If you want utc and milliseconds value, you can do
UTC Convertion
import pytz
from datetime import datetime
epoch: datetime = datetime.now().replace(tzinfo=pytz.utc)
print(epoch)

convert unix timestamp in milliseconds to UTC time & date formatting python3 [duplicate]

I have a Python datetime object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch.
How do I do this?
It appears to me that the simplest way to do this is
import datetime
epoch = datetime.datetime.utcfromtimestamp(0)
def unix_time_millis(dt):
return (dt - epoch).total_seconds() * 1000.0
In Python 3.3, added new method timestamp:
import datetime
seconds_since_epoch = datetime.datetime.now().timestamp()
Your question stated that you needed milliseconds, which you can get like this:
milliseconds_since_epoch = datetime.datetime.now().timestamp() * 1000
If you use timestamp on a naive datetime object, then it assumed that it is in the local timezone. Use timezone-aware datetime objects if this is not what you intend to happen.
>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000
1312908481000
Or the help of the time module (and without date formatting):
>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0
Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Documentation:
time.mktime
datetime.timetuple
You can use Delorean to travel in space and time!
import datetime
import delorean
dt = datetime.datetime.utcnow()
delorean.Delorean(dt, timezone="UTC").epoch
http://delorean.readthedocs.org/en/latest/quickstart.html
This is how I do it:
from datetime import datetime
from time import mktime
dt = datetime.now()
sec_since_epoch = mktime(dt.timetuple()) + dt.microsecond/1000000.0
millis_since_epoch = sec_since_epoch * 1000
Recommendedations from the Python 2.7 docs for the time module
from datetime import datetime
from calendar import timegm
# Note: if you pass in a naive dttm object it's assumed to already be in UTC
def unix_time(dttm=None):
if dttm is None:
dttm = datetime.utcnow()
return timegm(dttm.utctimetuple())
print "Unix time now: %d" % unix_time()
print "Unix timestamp from an existing dttm: %d" % unix_time(datetime(2014, 12, 30, 12, 0))
Here's another form of a solution with normalization of your time object:
def to_unix_time(timestamp):
epoch = datetime.datetime.utcfromtimestamp(0) # start of epoch time
my_time = datetime.datetime.strptime(timestamp, "%Y/%m/%d %H:%M:%S.%f") # plugin your time object
delta = my_time - epoch
return delta.total_seconds() * 1000.0
>>> import datetime
>>> import time
>>> import calendar
>>> #your datetime object
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 3, 19, 13, 0, 9, 351812)
>>> #use datetime module's timetuple method to get a `time.struct_time` object.[1]
>>> tt = datetime.datetime.timetuple(now)
>>> tt
time.struct_time(tm_year=2013, tm_mon=3, tm_mday=19, tm_hour=13, tm_min=0, tm_sec=9, tm_wday=1, tm_yday=78, tm_isdst=-1)
>>> #If your datetime object is in utc you do this way. [2](see the first table on docs)
>>> sec_epoch_utc = calendar.timegm(tt) * 1000
>>> sec_epoch_utc
1363698009
>>> #If your datetime object is in local timeformat you do this way
>>> sec_epoch_loc = time.mktime(tt) * 1000
>>> sec_epoch_loc
1363678209.0
[1] http://docs.python.org/2/library/datetime.html#datetime.date.timetuple
[2] http://docs.python.org/2/library/time.html
A bit of pandas code:
import pandas
def to_millis(dt):
return int(pandas.to_datetime(dt).value / 1000000)
import time
seconds_since_epoch = time.mktime(your_datetime.timetuple()) * 1000
A lot of these answers don't work for python 2 or don't preserve the milliseconds from the datetime. This works for me
def datetime_to_ms_epoch(dt):
microseconds = time.mktime(dt.timetuple()) * 1000000 + dt.microsecond
return int(round(microseconds / float(1000)))
Here is a function I made based on the answer above
def getDateToEpoch(myDateTime):
res = (datetime.datetime(myDateTime.year,myDateTime.month,myDateTime.day,myDateTime.hour,myDateTime.minute,myDateTime.second) - datetime.datetime(1970,1,1)).total_seconds()
return res
You can wrap the returned value like this : str(int(res))
To return it without a decimal value to be used as string or just int (without the str)
This other solution for covert datetime to unixtimestampmillis.
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long GetCurrentUnixTimestampMillis()
{
DateTime localDateTime, univDateTime;
localDateTime = DateTime.Now;
univDateTime = localDateTime.ToUniversalTime();
return (long)(univDateTime - UnixEpoch).TotalMilliseconds;
}

How to minus time with Python

I'd like to get the time before X seconds before
datetime.time.now(). For example, if the time.now() is 12:59:00, and I minus 59, I want to get 12:00:00.
How can I do that?
You can use time delta like this:
import datetime
print datetime.datetime.now() - datetime.timedelta(minutes=59)
import datetime
datetime.datetime.now() - datetime.timedelta(seconds=59)
Should do the trick
You can read more about timedelta on the documentation:
class datetime.timedelta
A duration expressing the difference between
two date, time, or datetime instances to microsecond resolution.
You need to use timedelta
from datetime import timedelta, datetime
d = datetime.now()
d = d - timedelta(minutes=59)
print d
You can try dateutil:
datetime.datetime.now() + dateutil.relativedelta.relativedelta(second=-60)

How to convert python timestamp string to epoch?

I have the following string:
mytime = "2009-03-08T00:27:31.807Z"
How do I convert it to epoch in python?
I tried:
import time
p = '%Y-%m-%dT%H:%M:%S'
int(time.mktime(time.strptime(s, p)))
But it does not work with the 31.807Z.
There are two parts:
Convert the time string into a broken-down time. See How to parse ISO formatted date in python?
Convert the UTC time to "seconds since the Epoch" (POSIX timestamp).
#!/usr/bin/env python
from datetime import datetime
utc_time = datetime.strptime("2009-03-08T00:27:31.807Z", "%Y-%m-%dT%H:%M:%S.%fZ")
epoch_time = (utc_time - datetime(1970, 1, 1)).total_seconds()
# -> 1236472051.807
If you are sure that you want to ignore fractions of a second and to get an integer result:
#!/usr/bin/env python
import time
from calendar import timegm
utc_time = time.strptime("2009-03-08T00:27:31.807Z", "%Y-%m-%dT%H:%M:%S.%fZ")
epoch_time = timegm(utc_time)
# -> 1236472051
To support timestamps that correspond to a leap second such as Wed July 1 2:59:60 MSK 2015, you could use a combination of time.strptime() and datetime (if you care about leap seconds you should take into account the microseconds too).
You are missing .%fZ from your format string.
p = '%Y-%m-%dT%H:%M:%S.%fZ'
The correct way to convert to epoch is to use datetime:
from datetime import datetime
p = '%Y-%m-%dT%H:%M:%S.%fZ'
mytime = "2009-03-08T00:27:31.807Z"
epoch = datetime(1970, 1, 1)
print((datetime.strptime(mytime, p) - epoch).total_seconds())
Or call int if you want to ignore fractions.
dateutil has recently been added back to python packages, it's an easy one liner that handles formatting on its own.
from dateutil import parser
strtime = '2009-03-08T00:27:31.807Z'
epoch = parser.parse(strtime).timestamp()
dateutil is the only library i have found that correctly deals with the timezone offset identitifier (Z)
pip install python-dateutil
then
from dateutil.parser import parse as date_parse
print date_parse("2009-03-08T00:27:31.807Z")
#get timestamp
import calendar
dt = date_parse("2009-03-08T00:27:31.807Z")
timestamp1 = calendar.timegm(dt.timetuple())
Code:
import datetime
epoch = datetime.datetime(1970, 1, 1)
mytime = "2009-03-08T00:27:31.807Z"
myformat = "%Y-%m-%dT%H:%M:%S.%fZ"
mydt = datetime.datetime.strptime(mytime, myformat)
val = (mydt - epoch).total_seconds()
print(val)
> 1236472051.81
repr(val)
> '1236472051.807'
Notes:
When using time.strptime(), the returned time.struct_time does not support sub-second precision.
The %f format is for microseconds. When parsing it need not be the full 6 digits.
Python 3.7+ The string format in question can be parsed by strptime:
from datetime import datetime
datetime.strptime("2009-03-08T00:27:31.807Z", '%Y-%m-%dT%H:%M:%S.%f%z')
>>> datetime.datetime(2009, 3, 8, 0, 27, 31, 807000, tzinfo=datetime.timezone.utc)
Another option using the built-in datetime.fromisoformat(): As mentioned in this thread linked by #jfs, fromisoformat() doesn't parse the 'Z' character to UTC although this is part of the RFC3339 definitions. A little work-around can make it work - some will consider this nasty but it's efficient after all.
from datetime import datetime
mytime = "2009-03-08T00:27:31.807Z"
datetime.fromisoformat(mytime.replace("Z", "+00:00")).timestamp()
>>> 1236472051.807
This code works in Python 3.6 to convert a datetime string to epoch in UTC or local timezone.
from datetime import datetime, timedelta
from dateutil.tz import tzutc, tzlocal
mydate = '2020-09-25'
mytime = '06:00:00'
epoch1970 = datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
myepochutc = int((datetime.strptime(mydate + ' ' + mytime, "%Y-%m-%d %H:%M:%S").replace(tzinfo=tzutc()) - epoch1970).total_seconds()*1000)
myepochlocal = int((datetime.strptime(mydate + ' ' + mytime, "%Y-%m-%d %H:%M:%S").replace(tzinfo=tzlocal()) - epoch1970).total_seconds()*1000)
#epoch will be in milliseconds
print(myepochutc) #if mydate/mytime was in utc
print(myepochlocal) #if mydate/mytime was in local timezone

Convert a time-only string such as "6:02PM" to a datetime object?

I have an input that is given in %I:%M%p (ex. "6:02PM").
I'm trying to input into this code to find the difference between now and then:
import datetime
now = datetime.now()
then = "6:02PM"
tdelta = now - then
import datetime as dt
now = dt.datetime.now()
then = dt.datetime.combine(now, dt.datetime.strptime("6:02PM", "%I:%M%p").time())
print(then)
# 2012-08-26 18:02:00
tdelta = now - then
print(tdelta)
# -1 day, 20:53:25.190721

Categories