Compare if datetime.timedelta is between two values - python

I have a datetime.timedelta time object in python (e.g. 00:02:00) I want to check if this time is less than 5 minutess and greater then 1 minute.
I'm not sure how to construct a timedelta object and I'm also not sure if this is the right format to compare times. Would anyone know the most efficient way to do this?

So if you start with a string that's rigorously and precisely in the format 'HH:MM:SS', timedelta doesn't directly offer a string-parsing function, but it's not hard to make one:
import datetime
def parsedelta(hhmmss):
h, m, s = hhmmss.split(':')
return datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s))
If you need to parse many different variants you'll be better off looking for third-party packages like dateutil.
Once you do have timedelta instance, the check you request is easy, e.g:
onemin = datetime.timedelta(minutes=1)
fivemin = datetime.timedelta(minutes=5)
if onemin < parsedelta('00:02:00') < fivemin:
print('yep')
will, as expected, display yep.

Related

Convert ISO 8601 time format to UNIX timestamp (epoch) and back again without losing fractional seconds?

Python methods to convert ISO 8601 time format to UNIX timestamp (epoch) and back again without losing fractional seconds?
I found several examples, but all the examples seem to drop the fractional seconds at some point in the conversion. Example below...
The issue seems to be the initial conversion to UNIX timestamp (epoch). Code below.
def ISO8601ToEpoch(theString):
from datetime import datetime
import calendar
return calendar.timegm(datetime.strptime(theString, "%Y-%m-%dT%H:%M:%S.%f").timetuple())
def EpochToISO8601(theEpoch):
from datetime import datetime
return datetime.fromtimestamp(theEpoch).isoformat()
#
print 'Original Time {0}'.format('2018-04-27T04:19:51.050937')
theTime=ISO8601ToEpoch('2018-04-27T04:19:51.050937')
print 'Time {0}'.format(theTime)
print 'Original Time {0}'.format(EpochToISO8601(theTime)
This results as...
Original Time 2018-04-27T04:19:51.050937
Time 1524802791
Original Time 2018-04-27T04:19:51
Is there a way to get timetuple to not hack the fractional seconds?
The problem here is that you're converting a datetime—which understands microseconds—into a timetuple—which doesn't.1
The obvious fix is just to not do that.
If you want to convert a datetime object to a timestamp, just use the timestamp method, the same way you already use the fromtimestamp classmethod to go the other way.
1. You might be able to trick a timetuple into holding a float instead of an int for seconds. But then you'd be breaking the invariants of the type. And, more importantly, defeating the entire purpose of the type, which is to be identical to a 1980s-style C struct tm. And likely also breaking the timegm function, which probably just calls the C function of the same name. (Most of the time module is a thin wrapper around C's <time.h>, as opposed to datetime, which is a friendly module designed for Python.) And then timegm is documented to return an integral type, so even if you got that far, it would all be for nothing.
I think this is correct... but if not I am sure someone will point out what I missed.
>>> import datetime as datetime
>>> import dateutil.parser
>>> import time
# Create a sample UNIX timestamp...
>>> t=time.time()
>>> t
1478266530.573583
# Convert the time stamp sample to ISO format...
>>> i=datetime.datetime.utcfromtimestamp(t).isoformat()
>>> i
'2016-11-04T13:35:30.573583'
# Convert ISO format to UNIX time stamp...
>>> d=dateutil.parser.parse(i)
>>> d
datetime.datetime(2016, 11, 4, 13, 35, 30, 573583)
>>> s=(time.mktime(d.timetuple())*1e3+d.microsecond/1e3)/1e3
>>> s
1478266530.5735831
It is not a perfect conversion given the number of fractional digits of the resulting timestamp but close enough for my need. I am sure the ISO format is a point of debate, but the format matches the typical format I expect to encounter, this is of course the lack of the 'Z' qualifier.

get time difference in seconds for time referring to another timezone

I intend to find the time difference between two time variables in seconds. The issue here is that I am referring to time in a different zone. I have managed to find a solution, but it is a mix of pandas.datetime function and python datetime library. I guess, the objective can be achieved with just pandas/numpy alone and with fewer lines of code. below is my code, appreciate any guidance on how can i achieve the final_output more efficiently.
import pandas as pd
from datetime import timedelta
local_time = pd.to_datetime('now').tz_localize('UTC').tz_convert('Asia/Dubai')
t1 = timedelta(hours=local_time.now('Asia/Dubai').hour, minutes=local_time.now('Asia/Dubai').minute)
t2 = timedelta(hours=9, minutes=14)
final_output = (t2 - t1).seconds
You may want to convert both times to UTC, then find the difference. Programmers usually like to work with UTC until the time reaches the front end.

Efficient way for python date string manipulation

I want to turn '07/18/2013' to '07/2013' and there are a lot of these strings to be processed. What would be the most efficient way to do it?
I am thinking of using
''.join(['07/18/2013'[0:3],'07/18/2013'[6:]])
Look into strftime and strptime.
Assuming you start with the string s you can put it into a datetime object using strptime then take that back out into a string with only the necessary fields using strftime. I didn't actually run this code so I don't know if it is perfect, but the idea is here.
temp = datetime.strptime.(s, "%m/%D/%Y")
final = temp.strftime(%m/%Y")
You can find info on the datetime functions here https://docs.python.org/2/library/datetime.html
Use datetime module:
import datetime
print datetime.datetime.strptime("07/18/2013", '%m/%d/%Y').strftime('%m/%Y')

Python script: convert random date formats to fixed yyyy-mm-dd

I'm quite new to python and don't know much about it but i need to make a small script that when someone inputs a date in any format , it would then converts it in to yyyy-mm-dd format.
The script should be able to share elements of the entered date, and identify patterns.
It might be easy and obvious to some but making one by my self is over my head.
Thanks in advance!
This is a difficult task to do yourself; you might want to take a look at dateutil which has a rather robust parse() method that you can use to try and parse arbitrarily formatted date strings.
You can do something like this (not tested)
import locale
import datetime
...
parsedDate = datetime.strptime(your_string, locale.D_FMT)
print datetime.strftime(parsedDate, "%Y-%M-%d")
This assumes that the user will use its own local convention for dates.
You can use strftime for output (your format is "%Y-%M-%d").
For parsing input there's a corresponding function - strptime. But you won't be able to handle "any format". You have to know what you're getting in the first place. Otherwise you wouldn't be able to tell a difference between (for example) American and other dates. What does 01.02.03 mean for example? This could be:
yy.mm.dd
dd.mm.yy
mm.dd.yy

How to generate a fixed-length hash based on current date and time in Python?

I want to generate a fixed-length (say 10 characters) hash based on current date & time. This hash will be append to names of the uploaded files from my users. How can I do that in Python?
Batteries included:
Python3
import hashlib
import time
hashlib.sha1().update(str(time.time()).encode("utf-8"))
print(hashlib.sha1().hexdigest())
print(hashlib.sha1().hexdigest()[:10])
Python2
import hashlib
import time
hash = hashlib.sha1()
hash.update(str(time.time()))
print hash.hexdigest()
print hash.hexdigest()[:10]
I think my comment is a reasonable answer so I am going to post it. The code uses the python time() function to get the number of seconds since the unix epoch:
import time
import datetime
ts = int(time.time()) # this removes the decimals
# convert the timestamp to a datetime object if you want to extract the date
d = datetime.datetime.fromtimestamp(ts)
The time stamp is currently a 10 digit integer that can easily be converted back to a datetime object for other uses. If you want to further shrink the length of the timestamp you could encode the number in hexadecimal or some other format. ie.
hex(int(time.time()))
This reduces the length to 8 characters if you remove the 0x prefix
EDIT:
In your comment you specified that you don't want people to figure out the original date so I would suggest doing something like:
hex(int(time.time() + 12345))[2:] #The [2:] removes the 0x prefix
Just chose a number and remember to subtract it when you are trying to extract the timestamp. Without knowing this number the user would have a very difficult time inferring the real date from your code.
int(stamp,16) - 12345
import time
'{0:010x}'.format(int(time.time() * 256))[:10]
Check out strftime for python. You can format the date/time string any number of ways to get the 'look' you want.
What about changing the base of current milliseconds since epoch. For example, in JavaScript, changing to base 36:
Date.now().toString(36)
Results in :
"jv8pvlbg"
That should be a safe hash, up to milliseconds, respect date order and smaller than 10.
The only thing is that is not safe, but in your case security is not important right?
Sorry I don't have the answer for python, but it should by straightforward and should nor require any library. My two cents.

Categories