I have following formats of data
start = '10:00:00'
end = '12:05:00'
My interval time wanna show like simple 2 hours 5 minutes 0 second
in this case i've used datetime and timedelta
code
from datetime import datetime, timedelta
start = '10:00:00'
end = '12:05:00'
FMT = '%H:%M:%S'
interval_time = datetime.strptime(end, FMT) - datetime.strptime(start, FMT)
print(interval_time)
if interval_time.days < 0:
tdiff = timedelta(days=0,
seconds=interval_time.seconds, microseconds=interval_time.microseconds)
print(tdiff)
This condition is false, Cause here is no day yet and here i wanna use hours instead of day.
Any help would be appreciated.
Thanks
'
Related
I have a date variable calls today_date as below. I need to get the 1st calendar day of the current and next month.
In my case, today_date is 4/17/2021, I need to create two more variables calls first_day_current which should be 4/1/2021, and first_day_next which should be 5/1/2021.
Any suggestions are greatly appreciated
import datetime as dt
today_date
'2021-04-17'
Getting just the first date of a month is quite simple - since it equals 1 all the time. You can even do this without needing the datetime module to simplify calculations for you, if today_date is always a string "Year-Month-Day" (or any consistent format - parse it accordingly)
today_date = '2021-04-17'
y, m, d = today_date.split('-')
first_day_current = f"{y}-{m}-01"
y, m = int(y), int(m)
first_day_next = f"{y+(m==12)}-{m%12+1}-01"
If you want to use datetime.date(), then you'll anyway have to convert the string to (year, month, date) ints to give as arguments (or do today_date = datetime.date.today().
Then .replace(day=1) to get first_day_current.
datetime.timedelta can't add months (only upto weeks), so you'll need to use other libraries for this. But it's more imports and calculations to do the same thing in effect.
I found out pd.offsets could accomplish this task as below -
import datetime as dt
import pandas as pd
today_date #'2021-04-17' this is a variable that is being created in the program
first_day_current = today_date.replace(day=1) # this will be 2021-04-01
next_month = first_day_current + pd.offsets.MonthBegin(n=1)
first_day_next = next_month.strftime('%Y-%m-%d') # this will be 2021-05-01
my time zone is "Australia/Melbourne" (I have multiple zones like this when I give this to my function) and I need the output like this ASET(GMT +10). How can I reach my answer?
Thank you
assuming you have date and time available (see my comment), the easiest way is probably strftime:
from datetime import datetime
from dateutil import tz
timezone = tz.gettz("Australia/Melbourne")
dt = datetime.now(timezone)
print(f"{dt.strftime('%Z')}(GMT{dt.strftime('%z')})")
# AEST(GMT+1000)
If you exactly want to get the specified output, I suppose you have to go a little more sophisticated:
total_minutes, seconds = divmod(dt.utcoffset().total_seconds(), 60)
hours, minutes = divmod(total_minutes, 60)
utcoff = f"{int(hours):+d}:{int(minutes):02d}" if minutes else f"{int(hours):+d}"
print(f"{dt.strftime('%Z')}(GMT{utcoff})")
# AEST(GMT+10)
I want to add 10 days to s so I try the following
import datetime
s= '01/11/2018'
add = s + datetime.timedelta(days = 10)
But I get an error
TypeError: must be str, not datetime.timedelta
so I try
add = s + str(datetime.timedelta(days = 10))
And I get
'01/11/201810 days, 0:00:00'
But this is not what I am looking for.
I would like the following output where 10 days are added to s
'01/21/2018'
I have also looked Adding 5 days to a date in Python but this doesnt seem to work for me
How do I get my desired output?
Your s is a string, not a datetime. Python knows how to add a string to a string and a datetime to a timedelta, but is pretty confused about you wanting to add a string and a timedelta.
datetime.datetime.strptime('01/11/2018', '%m/%d/%Y') + datetime.timedelta(days = 10)
I have been studying Python by myself since a month ago.
I want to make a duration calculator that shows the total time of each different duration.
For instance, there are two different flights I have to take, and I want to get the total time I would be in the airplanes. It goes like this.
a = input('Enter the duration: ') #11h40m
b = input('Enter the duration: ') #13h54m
#it may show the total duration
01d01h34m
Try this :
Edit : I tried to use strftime to format the 'duration' but had some issues with day.
So I did it manually (you can format it the way you wish)
import datetime
import time
# Convert str to strptime
a_time = datetime.datetime.strptime("11h40m", "%Hh%Mm")
b_time = datetime.datetime.strptime("13h54m", "%Hh%Mm")
# Convert to timedelta
a_delta = datetime.timedelta(hours = a_time.hour,minutes=a_time.minute)
b_delta = datetime.timedelta(hours = b_time.hour,minutes=b_time.minute)
duration = (a_delta + b_delta)
print(str(duration.days) + time.strftime('d%Hh%Mm', time.gmtime(duration.seconds)))
'1d01h34m'
I have a question very similar to this one and this one but I'm stuck on some rounding issue.
I have a time series from a netCDF file and I'm trying to convert them to a datetime format. The format of the time series is in 'days since 1990-01-01 00:00:00'. Eventually I want output in the format .strftime('%Y%m%d.%H%M'). So for example I read my netCDF file as follows
import netCDF4
nc = netCDF4.Dataset(file_name)
time = np.array(nc['time'][:])
I then have
In [180]: time[0]
Out[180]: 365
In [181]: time[1]
Out[181]: 365.04166666651145
I then did
In [182]: start = datetime.datetime(1990,1,1)
In [183]: delta = datetime.timedelta(time[1])
In [184]: new_time = start + delta
In [185]: print(new_time.strftime('%Y%m%d.%H%M'))
19910101.0059
Is there a a way to "round" to the nearest hour so I get 19910101.0100?
You can round down with datetime.replace(), and round up by adding an hour to the rounded down value using datetime.timedelta(hours=1).
import datetime
def round_to_hour(dt):
dt_start_of_hour = dt.replace(minute=0, second=0, microsecond=0)
dt_half_hour = dt.replace(minute=30, second=0, microsecond=0)
if dt >= dt_half_hour:
# round up
dt = dt_start_of_hour + datetime.timedelta(hours=1)
else:
# round down
dt = dt_start_of_hour
return dt
Note that since we're using replace the values we're not replacing (like the timezone - tzinfo) will be preserved.
I don't think datetime provides a way to round times, you'll have to provide the code to do that yourself. Something like this should work:
def round_to_hour(dt):
round_delta = 60 * 30
round_timestamp = datetime.datetime.fromtimestamp(dt.timestamp() + round_delta)
round_dt = datetime.datetime.fromtimestamp(round_timestamp)
return round_dt.replace(microsecond=0, second=0, minute=0)