Given I have a timestamp:
date_time_str = '2019-09-10T13:48:06+0200'
How can I calculate the time difference between the current time and this datetime?
I've got it so far with an impression of strong wrongdoing - this should be possible in a far simpler way:
from datetime import datetime, timezone
import time
date_time_str = '2019-09-10T13:48:06+0200'
format = '%Y-%m-%dT%H:%M:%S%z'
date_time_obj = datetime.strptime(date_time_str, format)
now = datetime.now()
now_time = now.strftime(format)
print(now_time)
now=datetime.strptime(datetime.fromtimestamp(int(time.time()), tz=timezone.utc).isoformat(), format)
print("now is: %s" % now)
print(now-time_obj)
The above program does not work because the current time comes out in a slightly different formatting:
'2019-09-10T15:56:11+00:00'
That is, if you run the above script for example Python 3.6.5, you get the error:
ValueError: time data '2019-09-10T18:18:09+00:00' does not match format '%Y-%m-%dT%H:%M:%S%z'
The mismatch is in the timezone format, "+00:00" vs. "+0200".
You can use datetime.now() to get the current datetime in utc:
# Same as your code
from datetime import datetime, timezone
date_time_str = '2019-09-10T13:48:06+0200'
format = '%Y-%m-%dT%H:%M:%S%z'
date_time_obj = datetime.strptime(date_time_str, format)
# Added:
print(datetime.now(tz=timezone.utc))
# 2019-09-10 18:35:48.066548+00:00
print(datetime.now(tz=timezone.utc) - date_time_obj)
# 6:47:42.066548
Related
I have data with the date format as follows:
date_format = 190410
year = 19
month = 04
date = 10
I want to change the date format, to be like this:
date_format = 10-04-2019
How do I solve this problem?
>>> import datetime
>>> date = 190410
>>> datetime.datetime.strptime(str(date), "%y%m%d").strftime("%d-%m-%Y")
'10-04-2019'
datetime.strptime() takes a data string and a format, and turns that into datetime object, and datetime objects have a method called strftime that turns datetime objects to string with given format. You can look what %y %m %d %Y are from here.
This is what you want(Notice that you have to change your format)
import datetime
date_format = '2019-04-10'
date_time_obj = datetime.datetime.strptime(date_format, '%Y-%m-%d')
print(date_time_obj)
Here is an other example
import datetime
date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)
You can also do this
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
print(date)
There are many ways to achieve what you want.
I'm new to python and I'm trying to get the actual minutes passed every day since 7:00.
I am using mktime to get now_date1 and now_date2 in seconds, and then the plan it's to subtract and divide by 60 to get the minutes.
But I get the following error:
AttributeError: 'str' object has no attribute 'timetuple'
It's this the correct approach?
Here it's the code
import time
import pytz
from datetime import datetime
from time import mktime as mktime
now_date = datetime.now(pytz.timezone('Europe/Bucharest'))
now_date1 = now_date.strftime('%H:%M:%S')
now_date2 = now_date.strftime('7:00:00')
# Convert to Unix timestamp
d1_ts = time.mktime(now_date1.timetuple())
strftime returns a string. Not what you want.
You were pretty close, but there's no need to put time in the mix. Just modify your code like this and use time delta from datetime (inspired by How to calculate the time interval between two time strings):
import pytz
from datetime import datetime
now_date = datetime.now(pytz.timezone('Europe/Bucharest'))
from datetime import datetime
FMT = '%H:%M:%S'
now_date1 = now_date.strftime(FMT)
now_date2 = now_date.strftime('7:00:00')
tdelta = datetime.strptime(now_date1, FMT) - datetime.strptime(now_date2, FMT)
print(tdelta)
I get: 6:40:42 which seems to match since it's 12:42 here.
To get the result in minutes just do:
tdelta.seconds//60
(note that the dates have only correct hour/time/seconds, the year, month, etc.. are 1900 ... since they're not used)
I think something like this might work:
import time
import datetime
from time import mktime as mktime
#current time
now_date = datetime.datetime.now()
#time at 7am
today = datetime.date.today()
now_date2 = datetime.datetime(today.year, today.month, today.day, 7, 0, 0, 0)
#difference in minutes
(now_date - now_date2).days * 24 * 60
I am trying to convert a datestamp of now into Unix TimeStamp, however the code below seems to be hit but then just jumps to the end of my app, as in seems to not like the time.mktime part.
from datetime import datetime
import time
now = datetime.now()
toDayDate = now.replace(hour=0, minute=0, second=0, microsecond=0)
newDate = time.mktime(datetime.strptime(toDayDate, "%Y-%m-%d %H:%M:%S").timetuple())
print(newDate)
Change
newDate = time.mktime(datetime.strptime(toDayDate, "%Y-%m-%d %H:%M:%S").timetuple())
to
newDate = time.mktime(datetime.timetuple())
as an example I did:
from datetime import datetime
from time import mktime
t = datetime.now()
unix_secs = mktime(t.timetuple())
and got unix_secs = 1488214742.0
Credit to #tarashypka- use t.utctimetuple() if you want the result in UTC (e.g. if your datetime object is aware of timezones)
You could use datetime.timestamp() in Python 3 to get the POSIX timestamp instead of using now().
The value returned is of type float. timestamp() relies on datetime which in turn relies on mktime(). However, datetime.timestamp() supports more platforms and has a wider range of values.
I'm given a timestamp (time since the epoch) and I need to convert it into this format:
yyyy/mm/dd hh:mm
I looked around and it seems like everyone else is doing this the other way around (date to timestamp).
If your answer involves dateutil that would be great.
Using datetime instead of dateutil:
import datetime as dt
dt.datetime.utcfromtimestamp(seconds_since_epoch).strftime("%Y/%m/%d %H:%M")
An example:
import time
import datetime as dt
epoch_now = time.time()
sys.stdout.write(str(epoch_now))
>>> 1470841955.88
frmt_date = dt.datetime.utcfromtimestamp(epoch_now).strftime("%Y/%m/%d %H:%M")
sys.stdout.write(frmt_date)
>>> 2016/08/10 15:09
EDIT: strftime() used, as the comments suggested.
I need to convert a value in microseconds to the format '%Y-%m-%d %H:%M:%S' and apply timezone information to adjust the output. I tried:
datatime.datetime.fromtimestamp(timestamp).strftime('format')
but that is not timezone aware. How do I apply timezone information when converting from microseconds to a date and time string?
To convert the timestamp ("seconds since the epoch") to time in UTC as a naive datetime object:
#!/usr/bin/env python
from datetime import datetime
timestamp = 1422025533
utc_time = datetime.utcfromtimestamp(timestamp)
print("Time is = %s" % utc_time)
# -> Time is = 2015-01-23 15:05:33
If you want to get the value in a specific timezone as an aware datetime object; you should use pytz module:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
tz = pytz.timezone('Europe/London')
timestamp = 1422025533
london_time = datetime.fromtimestamp(timestamp, tz)
print("Time is = %s" % london_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
# -> Time is = 2015-01-23 15:05:33 GMT+0000
I think Delorean is the right lib you should use.
Delorean is a library for clearing up the inconvenient truths that arise dealing with datetimes in
from datetime import datetime
from pytz import timezone
EST = "US/Eastern"
UTC = "UTC"
d = datetime.utcnow()
utc = timezone(UTC)
est = timezone(EST)
d = utc.localize(d)
d = est.normalize(d)
print d