datetime strptime method for format HH:MM:SS.MICROSECOND - python-2.7

I'm trying to investigate the Python time striptime method to decompose a time represented as 11:49:57.74. The standard %H, %M, %S are able to decompose the hour , minute , second. However, since the data is a string ( which is taken in python pandas column as datatype object, the Milliseconds after the decimal second is left uninterpreted. Hence, I get an error. Could someone please advise how to parse the example so that the seconds and microseconds are correctly interpreted from the time string ?
I would then use them to find the time delta between two time stamps.

I don't know if I had correctly understood your question.
So, to convert that string time to datetime and calculate the timedelta between two times you need to do as follow:
timedelta = str() #declare an empty string where save the timedelta
my_string = '11:49:57.74' # first example time
another_example_time = '13:49:57.74' #second example time, invented by me for the example
first_time = datetime.strptime(my_string, "%H:%M:%S.%f") # extract the first time
second_time = datetime.strptime(another_example_time , "%H:%M:%S.%f") # extract the second time
#calculate the time delta
if(first_time > second_time):
timedelta = first_time - second_time
else:
timedelta = second_time - first_time
print "The timedelta between %s and %s is: %s" % (first_time, second_time, timedelta)
Here obviusly you don't have any date, so the datetime library as default use 1900-01-01 as you can see in the result of the print:
The timedelta between 1900-01-01 11:49:57.740000 and 1900-01-01 13:49:57.740000 is: 2:00:00
I hope this solution is what you need. Next time provide a little bit more information please, or share an example with the code that you have tried to write.

Related

How to handle datetime vlaues in python?

I have a datetime in format = '2020-05-01'. I want the output to be 2020-05-01 00:00:00.
I use this simple code to achieve this but I am missing the time part.
datetime.strptime(month, "%Y-%m-%d")
I am using python2. Does anyone have any idea on how to achieve this. This seems like a really simple problem but for some reason I am not able to achieve it.
Your one line of code already generates a datetime value which should be set to midnight (the default value for no explicit time component). If you want to view this data with its time component, then use strftime with an appropriate format mask:
month = '2020-05-01'
dt = datetime.strptime(month, "%Y-%m-%d")
dt_out = dt.strftime("%Y-%m-%d %H:%M:%S")
print(dt_out)
This prints:
2020-05-01 00:00:00
x = datetime.strptime(month, "%Y-%m-%d")
x.strftime(month, "%Y-%m-%d %H:%M:%S")
Source:
https://www.programiz.com/python-programming/datetime/strftime

Subtracting two datetimes from each other and returning in HH:MM:SS in python 2.7

I have two date-time strings that I wish to subtract from each other and want to return a answer in
the HH:MM:SS format using python 2.7. For Example I have "2019-01-22 10:46:34" and "2019-01-22 10:30:34" and want it to return something like this 00:16:00. I have tried converting the times to integers but can't seem to convert back. I have also tried the datetime module. Below is a rudimentary example of something I tried that I wish to convert into a function.
from datetime import datetime
a = "2019-01-22 10:46:34"
b = "2019-01-22 10:30:25"
c = a-b
print(datetime.time(c, '%Y-%m-%d %H:%M:%S')
I have been working on this problem for a few days so any help would be much appreciated.
Take a look at the timedelta Object.
With that you can get the difference of two datetime Objects in Seconds and then you can calc the Minutes Hours etc.
Example you have two datetime objects a and b, c will be the timedelta object:
import datetime
# datetime object (year, month, day, hour, minute, second)
a = datetime.datetime.strptime("2019-01-22 10:46:34", "%Y-%m-%d %H:%M:%S")
b = datetime.datetime.strptime("2019-01-22 10:30:25", "%Y-%m-%d %H:%M:%S")
# returns timedelta object
c = a-b
print('Difference: ', c)
# return (minutes, seconds)
minutes = divmod(c.seconds, 60)
print('Difference in minutes: ', minutes[0], 'minutes',
minutes[1], 'seconds')
EDIT: divmod() is used to get batter result in terms of minutes and seconds, but you could also just write
minutes = c.seconds / 60
print('Difference in minutes: ', minutes)
Output: Difference in minutes: 16 minutes 9 seconds

Python - Timestamp Conversion

I have converted some sensor data into CSV format. The data contains a timestamp attribute that is divided into two parts as follows:
measurement_timestamp_begin:
seconds: 3733032665
fractions: 3056174174
I need to convert this into standard UNIX timestamp format. I saw several posts for doing the conversion but each method receives a single argument. I don't understand the fraction part. Does it mean seconds.fraction? e.g. 3733032665.3056174174.
Following code converts above mentioned timestamp format to standard UNIX timestamp format.
#!/usr/bin/env python
import datetime, time
unix_epoch = datetime.date(*time.gmtime(0)[0:3])
ntp_epoch = datetime.date(1900, 1, 1)
ntp_delta = (unix_epoch - ntp_epoch).days * 24 * 3600
def ntp_to_unix_time(date):
return (date - ntp_delta)
print datetime.datetime.fromtimestamp(int(ntp_to_unix_time(3733032665.3056174174))).strftime('%Y-%m-%d %H:%M:%S')

How to convert time.strptime into an integer for datatime.date() Python 2

How would I convert the result from strptime into an integer value or a value that can be used by date.date()?
convertTOdate = time.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
duedate = datetime.datetime(convertTOdate)
A Solution on stackoverflow was to do:
Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.
from time import mktime
from datetime import datetime
dt = datetime.fromtimestamp(mktime(struct))
I do not want to get the local time as it would not work with my function
I am using Python 2
Thank you
You can use the following approach.
from datetime import datetime
def time_in_seconds(dt):
epoch = datetime.utcfromtimestamp(0)
delta = dt - epoch
return delta.total_seconds()
convertTOdate = datetime.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
duedate = time_in_seconds(convertTOdate)
returns 1184752999.0 which is equivalent to 2007-07-18 10:03:19
duedate = datetime.utcfromtimestamp(duedate)
print duedate
Just remember before using the following two:
fromtimestamp give you the date and time in local time and utcfromtimestamp gives you the date and time in UTC.

Would DateTimeField() work if I have time in this format 1/7/11 9:15 ? If not what would?

I am importing data from a JSON file and it has the date in the following format 1/7/11 9:15
What would be the best variable type/format to define in order to accept this date as it is? If not what would be the most efficient way to accomplish this task?
Thanks.
"What would be the best variable type/format to define in order to accept this date as it is?"
The DateTimeField.
"If not what would be the most efficient way to accomplish this task?"
You should use the datetime.strptime method from Python's builtin datetime library:
>>> from datetime import datetime
>>> import json
>>> json_datetime = "1/7/11 9:15" # still encoded as JSON
>>> py_datetime = json.loads(json_datetime) # now decoded to a Python string
>>> datetime.strptime(py_datetime, "%m/%d/%y %I:%M") # coerced into a datetime object
datetime.datetime(2011, 1, 7, 9, 15)
# Now you can save this object to a DateTimeField in a Django model.
If you take a look at https://docs.djangoproject.com/en/dev/ref/models/fields/#datetimefield, it says that django uses the python datetime library which is docomented at http://docs.python.org/2/library/datetime.html.
Here is a working example (with many debug prints and step-by-step instructions:
from datetime import datetime
json_datetime = "1/7/11 9:15"
json_date, json_time = json_datetime.split(" ")
print json_date
print json_time
day, month, year = map(int, json_date.split("/")) #maps each string in stringlist resulting from split to an int
year = 2000 + year #be ceareful here! 2 digits for a year may cause trouble!!! (could be 1911 as well)
hours, minutes = map(int, json_time.split(":"))
print day
print month
print year
my_datetime = datetime(year, month, day, hours, minutes)
print my_datetime
#Generate a json date:
new_json_style = "{0}/{1}/{2} {3}:{4}".format(my_datetime.day, my_datetime.month, my_datetime.year, my_datetime.hour, my_datetime.minute)
print new_json_style