How to convert time object to minutes in python - python

I have an output from a database(postgreSQL) in python. The time is encoded as timestamptz. We need to be able to convert the time into just minutes.
2015-07-09 13:45:08.266520+00:00
For example this would be 825 minutes.
I'm having issues with the datetime.datetime formating, I just need to be able to drop everything but hours and minutes and then convert to minutes.
time_format = '%H:%M'
time1 = datetime.strptime('2015-07-09 13:45:08.266520+00:00', time_format)
So I'm trying to sort a big list of times into certain intervals. I need these times to be in just minutes in order to do any math on them, I do not want to have to mess with time anymore. Thats why I'm trying to just covert them into minutes by taking the hours * 60 + minutes. Since this is in a time format I cannot do any of that.

Substract the DateTime from a DateTime with the the reference point in time, extract the total_seconds from the resulting TimeDelta and divide by 60.
(You did not give any code. So I can't give any code based on your's.)

dateutil takes a lot of the headache out of parsing a ISO 8601 stamp:
>>> import dateutil.parser
>>> dateutil.parser.parse('2015-07-09 13:45:08.266520+00:00')
datetime.datetime(2015, 7, 9, 13, 45, 8, 266520, tzinfo=tzutc())
Since you want the answer to be '825 minutes', algebraically, you must be seeking an offset from an epoch mark:
>>> import datetime as dt
>>> mark=dateutil.parser.parse('2015-07-09 13:45:08.266520+00:00')-dt.timedelta(minutes=825)
>>> mark
datetime.datetime(2015, 7, 9, 0, 0, 8, 266520, tzinfo=tzutc())
So now use mark as the basis to calculate minute offsets. (You probably mean to ignore microseconds in the base time mark)

I understand what you're trying to do. So you want to convert the timestamp you're getting from your DB into minutes. Basically 0:00 would be 0, 1:00 would be 60 and so on.
Timestamps are standard, so a dirty hack you could do is just pull the indices of the relevant information that you want and go from there.
time = "2015-07-09 13:45:08.266520+00:00"
data = time[11:18]
print data //Will be 13:45:08
Then you can do data operations from there.

Related

Date Time Format Unknown [duplicate]

This question already has answers here:
How to convert integer timestamp into a datetime
(3 answers)
Closed last year.
I am trying to figure out a time format used by someone else. In addition to the date, I have time with an example being the following:
1641859200000
I cant seem to figure out what time or date time format this is. It cannot be HHMMSS, because in this example the second is 85, which is not possible. Any idea what format this is, and how I can convert it using Python to HH:MM:SS ?
Thank you :)
You have a timestamp in seconds from Epoch since January 1, 1970 (midnight UTC/GMT). To convert to a datetime, use:
from datetime import datetime
print(datetime.fromtimestamp(1641859200000 / 1000))
# Output
2022-01-11 01:00:00
Note: you have to divide by 1000 because this timestamp contains milliseconds and Epoch should be in seconds.
This is a Unix-Timestamp.
You can convert in a human-readable format like this:
from datetime import datetime
timestamp = 1641859200000/1000
dt = datetime.fromtimestamp(timestamp)
print(dt)
Edit: didn't check the actual timestamp, whyever, this has to be divided by 1000 as done in the othe answer.
This probably is a unix timestamp https://en.wikipedia.org/wiki/Unix_time. The factor 1000 stems from a millisecond representation I think. Depends on, from where you got this stamp.
You can convert it using:
>>> datetime.datetime.fromtimestamp(1641859200000/1000)
datetime.datetime(2022, 1, 11, 1, 0)
Take a look at dateparser https://dateparser.readthedocs.io/.
It will help you figure out what the date and time is based on the range of input date strings:
pip install dateparser
>>> import dateparser
>>> dateparser.parse('1641859200000')
datetime.datetime(2022, 1, 11, 1, 0)
Your timestamp is miliseconds since Unix epoch in this case but if you ever run into similar problem dateparser could help you.
Regarding the second part of the question. Convertion to HH:MM:SS format
>> dt = datetime.datetime(2022, 1, 11, 1, 0)
>> dt.strftime("%H:%M:%S")
'01:00:00'
Additional info: Available Format Codes

How to convert HH:MM:SS time to decimal in Python

Assuming that I have the following date and time (June 12, 2017 07:10:43.340) that I stored in a dateime object. From that I have a timestamp object, as follows:
from datetime import *
timeH = datetime(2017, 6,12, 7, 10, 43, 340)
timeHstamp = timeH.timestamp()
What I want to obtain is a decimal representation of the time only. That is
7.178 which I calculated, manually, by dividing seconds over 60 (43.34/60), add it the minutes (10+0.7223), divide the total minutes by 60 (10.7223/60), and then add to hours (7+0.178). I know I can write a custom function that would output exactly what I need. However, I am wondering if there is any available methods that can achieve this.
I have searched stackoverflow and other sites; but, there doesn't seem to be function that does this in Python. This post provide something similar but in Matlab Convert hh:mm time to decimal time (Matlab)
One way using datetime.combine:
(datetime.combine(date.min, timeH.time()) - datetime.min).total_seconds()/3600
Output:
7.178611205555555

Convert epoch time (minute since reference time) to human readable time format

The question in the title seems to be familiar as I could see lot of example blog posts and SO posts. However, I couldn't find a question similar to the issue I am facing. I have a netcdf file in which variable time has a single data value 10643385. The unit of this time variable is minutes since 2000-01-01 00:00:00 which is different from many examples I found on the internet.I am also aware of the fact that actual value of time is 27-03-2020 05:45. My query is that how do I get this epoch value int to the date time format like `27-03-2020 05:45'. Here is the sample code I have been trying which results in the reference datetime rather than actual datetime of the file:-
print(datetime.datetime.fromtimestamp(int(epoch_time_value)).strftime('%Y-%m-%d %H:%M:%S'))
The above single line of code result in 1970-05-04 09:59:45. Can some one help me to get the correct date.
import datetime
t = datetime.datetime(2000, 1, 1) + datetime.timedelta(minutes=10643385)
outputs
datetime.datetime(2020, 3, 27, 5, 45)
Python epoch time is in seconds, so we must first convert this to seconds by multiplying by 60.
Python epoch time starts on 1, Jan, 1970. Since netcdf starts on 2000-01-01, we must adjust by adding the amount of seconds from 1970 to 2000 (which happens to be 946684800).
Putting these together we get:
>>> import datetime
>>> epoch_time_value = 10643385
>>> _epoch_time_value = epoch_time_value * 60 + 946684800
>>> print(datetime.datetime.fromtimestamp(int(_epoch_time_value)).strftime('%Y-%m-%d %H:%M:%S'))
2020-03-26 22:45:00
Then, there may be some shift (possibly +/- 12 hours) based on timezone, so make sure the timezones in your calculations are synced when you do this!

Human readable delta time text to Python `timedelta`

I have seen many examples on how to parse a human readable text containing a date/time to datetime structure or even seconds since "Epoch".
A few Pyhton libraries (e.g. parsedatetime or dateparser claim to be able to parse relative date/times (like "1min 47 seconds ago") but the end result is always anchored to a specific date/time.
Example using two mentioned libraries:
sdate="1 min 37 seconds ago"
dateparser.parse(sdate)
datetime.datetime(2019, 8, 19, 17, 20, 29, 325230)
pdtCal.parse(sdate)
(time.struct_time(tm_year=2019, tm_mon=8, tm_mday=19, tm_hour=17, tm_min=22, tm_sec=49, tm_wday=0, tm_yday=231, tm_isdst=-1), 2)
What I need, though, is something as simple as a timedelta object, but from what I could learn, the best I can do is to compute the timedelta by subtracting the parsed datetime from current time.
Obviously, this is not the same since I will be adding a sampling error (datetime.datetime.now() is running at a different time as the parser run).
So I ask, is there a simple yet relieble way in Python to parse this delta time text directly into a timedelta object or a scalar value (e.g seconds count)?
Thanks!
There is a way to specify "anchor date" in dateparser using settings:
In [1]: from dateparser import parse
In [2]: from datetime import datetime
In [3]: anchor_date = datetime(2020, 1, 1)
In [4]: parsed_date = parse('1 min 37 seconds ago', settings={'RELATIVE_BASE': anchor_date})
In [5]: parsed_date - anchor_date
Out[5]: datetime.timedelta(days=-1, seconds=86303)
Using the same date as relative base and in delta calculation ensures precise results.

Getting a lists of times in Python from 0:0:0 to 23:59:59 and then comparing with datetime values

I was working on code to generate the time for an entire day with 30 second intervals. I tried using DT.datetime and DT.time but I always end up with either a datetime value or a timedelta value like (0,2970). Can someone please tell me how to do this.
So I need a list that has data like:
[00:00:00]
[00:00:01]
[00:00:02]
till [23:59:59] and needed to compare it against a datetime value like 6/23/2011 6:38:00 AM.
Thanks!
Is there a reason you want to use datetimes instead of just 3 for loops counting up? Similarly, do you want to do something fancy or do you want to just compare against the time? If you don't need to account for leap seconds or anything like that, just do it the easy way.
import datetime
now = datetime.datetime.now()
for h in xrange(24):
for m in xrange(60):
for s in xrange(60):
time_string = '%02d:%02d:%02d' % (h,m,s)
if time_string == now.strftime('%H:%m:%S'):
print 'you found it! %s' % time_string
Can you give any more info about why you are doing this? It seems like you would be much much better off parsing the datetimes or using strftime to get what you need instead of looping through 60*60*24 times.
There's a great answer on how to get a list of incremental values for seconds for a 24-hour day. I reused a part of it.
Note 1. I'm not sure how you're thinking of comparing time with datetime. Assuming that you're just going to compare the time part and extracting that.
Note 2. The time.strptime call expects a 12-hour AM/PM-based time, as in your example. Its result is then passed to time.strftime that returns a 24-hour-based time.
Here's what I think you're looking for:
my_time = '6/23/2011 6:38:00 AM' # time you defined
from datetime import datetime, timedelta
from time import strftime, strptime
now = datetime(2013, 1, 1, 0, 0, 0)
last = datetime(2013, 1, 1, 23, 59, 59)
delta = timedelta(seconds=1)
times = []
while now <= last:
times.append(now.strftime('%H:%M:%S'))
now += delta
twenty_four_hour_based_time = strftime('%H:%M:%S', strptime(my_time, '%m/%d/%Y %I:%M:%S %p'))
twenty_four_hour_based_time in times # returns True

Categories

Resources