Python Time Subtraction Resulting into Time Tuple - python

I want to subtract 2 times and convert that into a time array.
I consulted this How to calculate the time interval between two time strings. Stating this following code
from datetime import datetime as dt
import time
print("Time Subtraction")
FMT = '%Y-%m-%d %H:%M:%S'
time_tuple = (2018, 1, 13, 13, 51, 18, 2, 317, 0)
time2_tuple = (2018, 1, 15, 13, 50, 18, 2, 317, 0)
s1 = time.strftime(FMT, time_tuple)
s2 = time.strftime(FMT, time2_tuple)
tdelta = dt.strptime(s2, FMT) - dt.strptime(s1, FMT)
print(tdelta)
The result is:
Time Subtraction
1 day, 23:59:00
But I want to get a tuple/print that will look like this
tuple = (0,0,1,23,59,0,2,317,0)
I usually use time not datetime so I am not sure what to do. Any ideas?

tdelta is a datetime.timedelta object, therefore you are printing the string representation of that object. You can get the days, hours, minutes, etc by performing simple arithmetic (since they are stored as fractions-of-days) on the attributes:
def days_hours_minutes(delta):
return delta.days, delta.seconds//3600, (delta.seconds//60)%60
You can add as many of these attributes to the tuple as you'd like.

Related

plot only the time from datetime objects in matplot lib

I have a list of date and time values with the format '2019-08-24 08:57:18.550' for example. I have successfully converted them into numbers that matplotlib understands using datetime with the code matplotlib.dates.date2num(points) however I am having trouble getting matplotlib to plot only the time, not the associated date.
The graph it creates has tick marks with labels such as 08-24 12 which I assume has the format "month-date hour". I would like it to only plot the time, ideally with the format "hour:minute" or something along those lines. How do I get matplotlib to do this?
If I understood correctly, and it is the current date/time that you are looking for, then:
>>> from datetime import datetime
>>> current_time = datetime.now()
>>> current_time
datetime.datetime(2020, 5, 18, 22, 4, 41, 425538)
#################(year, month, day, hour, minute, second, microsecond)
You can then format it (this is what I didn't quite understand what you were asking), but if you wanted hour:minute format then:
from datetime import datetime
time = datetime.now()
hour = time.hour
minute = time.minute
print(f"{hour}:{minute}")
You should note that datetime.datetime(2020, 5, 18, 22, 4, 41, 425538) was not iterable.

In python convert seconds from 1970 to hours since 1900

Have two data sets with different time format. One in epcoh time, seconds from 1/1/1970, and the other hours since 1/1/1900. Need to convert the first to the second one. How can I do that in python ?
Thanks
So, for starters, here are the necessary tools:
from datetime import datetime, timezone, timedelta
Then you need to establish the starting time:
atmos_epoch = datetime(1900, 1, 1, 0, 0, tzinfo=timezone.utc)
Then you can work with deltas to that time:
>>> d = datetime.now(timezone.utc) - atmos_epoch
>>> d
datetime.timedelta(days=43893, seconds=28215, microseconds=982930)
>>> d.total_seconds() / 60 / 60
1053439.8377730362
That last value is the difference in hours.
You can add deltas to that epoch timestamp:
>>> atmos_epoch + timedelta(hours=1000000)
datetime.datetime(2014, 1, 29, 16, 0, tzinfo=datetime.timezone.utc)
The other thing you talk about, seconds since 1970, are simply UNIX timestamps, which you can work with easily:
>>> datetime.now().timestamp()
1583395060.91666
>>> datetime.fromtimestamp(1500000000)
datetime.datetime(2017, 7, 14, 4, 40)
Now you have a way to convert from both values to datetime objects and from datetime objects to either value.

Substract current time to -GMT in python

I have a time which is 13:11:06 and i want to -GMT (i.e -0530). I can minus it by simply doing -5 by splitting the string taking the first digit (convert to int) and then minus it and then re-join. But then i get it in a format which is 8:11:06 which is not right as it should be 08:11:06, secondly its a lengthy process. Is there a easy way to get my time in -GMT format (08:11:06)
This is what i did to get -GMT time after getting the datetime
timesplithour = int(timesplit[1]) + -5
timesplitminute = timesplit[2]
timesplitseconds = timesplit[3]
print timesplithour
print timesplitminute
print timesplitseconds
print timesplithour + ":" + timesplitminute + ":" + timesplitseconds
You could use Python's datatime library to help you as follows:
import datetime
my_time = "13:11:06"
new_time = datetime.datetime.strptime("2016 " + my_time, "%Y %H:%M:%S") - datetime.timedelta(hours=5, minutes=30)
print new_time.strftime("%H:%M:%S")
This would print:
07:41:06
First it converts your string into a datetime object. It then creates a timedelta object allowing you to subtract 5 hours 30 minutes from the datetime object. Finally it uses strftime to format the resulting datetime into a string in the same format.
Use the datetime module:
from datetime import datetime, timedelta
dt = datetime.strptime('13:11:06', '%H:%M:%S')
time_gmt = (dt - timedelta(hours=5, minutes=30)).time()
print(time_gmt.hour)
print(time_gmt.minute)
print(time_gmt.second)
s = time_gmt.strftime('%H:%M:%S')
print(s)
Output
7
41
6
07:41:06
Note that this subtracts 5 hours and 30 minutes as initially mentioned in the question. If you really only want to subtract 5 hours, use timedelta(hours=5).
You can use datetimes timedelta.
print datetime.datetime.today()
>>> datetime.datetime(2016, 3, 3, 10, 45, 6, 270711)
print datetime.datetime.today() - datetime.timedelta(days=3)
>>> datetime.datetime(2016, 2, 29, 10, 45, 8, 559073)
This way you can subtract easily
Assuming the time is a datetime instance
import datetime as dt
t = datetime(2015,12,31,13,11,06)
#t.time() # gives time object. ie no date information
offset = dt.timedelta(hours=5,minutes=30) # or hours=5.5
t -= offset
t.strftime(("%H:%M:%S") # output as your desired string
#'18:41:06'
If the object is datetime and you don't care about DST, the simplest thing you can do is,
In [1]: from datetime import datetime
In [2]: curr = datetime.now()
In [3]: curr
Out[3]: datetime.datetime(2016, 3, 3, 9, 57, 31, 302231)
In [4]: curr.utcnow()
Out[4]: datetime.datetime(2016, 3, 3, 8, 57, 57, 286956)

Convert the unicode to datetime format

A function returns date and time in unicode format.
u'2014-03-06T04:38:51Z'
I wish to convert this to date and time format and subtract it with current datetime to get the number of days in between.
Thanks in advance
Check string is unicode
>>> import types
>>> type(u'2014-03-06T04:38:51Z') is types.UnicodeType
True
Converting strings to datetime:
>>> import datetime
>>> datetime.datetime.strptime(u'2014-03-06T04:38:51Z', '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2014, 3, 6, 4, 38, 51)
Subtract from today to
>>> import datetime
>>> today = datetime.datetime.today()
>>> yourdate = datetime.datetime.strptime(u'2014-03-06T04:38:51Z', '%Y-%m-%dT%H:%M:%SZ')
>>> difference = today - yourdate
print str(difference)
First you have to convert your string to a datetime.datetime object.
import datetime
then = datetime.datetime.strptime(u'2014-03-06T04:38:51Z', "%Y-%m-%dT%H:%M:%SZ")
then represents itself as datetime.datetime(2014, 3, 6, 4, 38, 51), which looks about right. Then you have to get today's date as a datetime.datetime.
now = datetime.datetime.now()
Finally subtract it from your date (or vice versa - the question didn't make it clear).delta is a datetime.timedelta object that stores increments in days, seconds and microseconds. The latter two are always positive, the first can be negative.
for delta in (now-then, then-now):
print(delta, "::", delta.days, delta.seconds, delta.microseconds)
This prints out:
-1 day, 20:18:14.250142 :: -1 73094 250142
3:41:45.749858 :: 0 13305 749858
Best try it with a few examples to convince yourself it's correct.

How to get the first and last second using datetime module in python?

How to get the first and last second in python using the DateTime module which means 00:00:01 and 23:59:59.
I want to get the six DateTime before today.
So, for example:
today is 12/10, and I want to get
12/9 00:00:01 and 23:59:59
...
12/4 00:00:01 and 23:59:59
Thank you very much.
Just use datetime.time.min and datetime.time.max:
>>> import datetime
>>> datetime.time.min
datetime.time(0, 0)
>>> datetime.time.max
datetime.time(23, 59, 59, 999999)
You can combine that with a datetime.date instance to get a full datetime.datetime instance:
>>> datetime.datetime.combine(datetime.date.today(), datetime.time.max)
datetime.datetime(2012, 12, 1, 23, 59, 59, 999999)
To re-use an existing datetime.datetime instance, use the .combine() method together with the .date() method on the datetime.datetime instance to create a new datetime.datetime instance:
>>> datetime.datetime.combine(datetime.datetime.now().date(), datetime.time.min)
datetime.datetime(2012, 12, 1, 0, 0)
To get a series of dates, use datetime.timedelta instances to create offsets. A series of dates relative to today is then easy:
today = datetime.date.today()
lastweek = today - datetime.timedelta(days=7)
for i in range(7):
aday = lastweek + datetime.timedelta(days=i)
first = datetime.datetime.combine(aday, datetime.time.min)
last = datetime.datetime.combine(aday, datetime.time.max)
print first, last
I had problems with the accepted answer not working with timezones (You can see my train of thought in the comments.
Here's what I came up with for use with pytz.
# utc_date_time should already be localized to UTC
# it should NOT be a naive date-time
def get_last_second_of_day_in_timezone(utc_date_time, local_timezone: str):
local_timezone = pytz.timezone(local_timezone)
due_date_in_timezone = utc_date_time.astimezone(local_timezone)
last_second_of_due_day_naive = datetime.combine(due_date_in_timezone, time.max)
last_second_of_due_day = local_timezone.localize(last_second_of_due_day_naive)
return last_second_of_due_day
And a unit test for it
def test_get_last_second_of_day_in_timezone__previous_day_utc(self):
utc_tz = pytz.timezone("UTC")
ten_pm_utc = utc_tz.localize(datetime(2022, 1, 1, hour=22))
bangladesh_timezone = "Asia/Dhaka"
# 10pm UTC is the next day in Dhaka, so this should be the second before midnight on the 2nd
last_second_of_jan_2_bangladesh = get_last_second_of_day_in_timezone(ten_pm_utc, bangladesh_timezone)
self.assertEqual(last_second_of_jan_2_bangladesh.year, 2022)
self.assertEqual(last_second_of_jan_2_bangladesh.month, 1)
self.assertEqual(last_second_of_jan_2_bangladesh.day, 2)
self.assertEqual(last_second_of_jan_2_bangladesh.hour, 23)
self.assertEqual(last_second_of_jan_2_bangladesh.minute, 59)
# This doesn't work on all machines, should find better check
# This is because pytz.timezone(bangladesh_timezone) is the offset from the late 1800s, which is +6:02 instead of +6:00
# self.assertEqual(last_second_of_jan_2_bangladesh.tzinfo, pytz.timezone(bangladesh_timezone))
# Which is (23 - 6 = 17) 17:59 UTC
last_second_of_jan_2_bangladesh_utc = last_second_of_jan_2_bangladesh.astimezone(utc_tz)
self.assertEqual(last_second_of_jan_2_bangladesh_utc.year, 2022)
self.assertEqual(last_second_of_jan_2_bangladesh_utc.month, 1)
self.assertEqual(last_second_of_jan_2_bangladesh_utc.day, 2)
self.assertEqual(last_second_of_jan_2_bangladesh_utc.hour, 17)
self.assertEqual(last_second_of_jan_2_bangladesh_utc.minute, 59)

Categories

Resources