Python - How to convert datetime data using toordinal considering the time - python

Let's assume that I have the following data:
25/01/2000 05:50
When I convert it using datetime.toordinal, it returns this value:
730144
That's nice, but this value just considers the date itself. I also want it to consider the hour and minutes (05:50). How can I do it using datetime?
EDIT:
I want to convert a whole Pandas Series.

An ordinal date is by definition only considering the year and day of year, i.e. its resolution is 1 day.
You can get the microseconds / milliseconds (depending on your platform) from epoch using
datetime.datetime.strptime('25/01/2000 05:50', '%d/%m/%Y %H:%M').timestamp()
for a pandas series you can do
s = pd.Series(['25/01/2000 05:50', '25/01/2000 05:50', '25/01/2000 05:50'])
s = pd.to_datetime(s) # make sure you're dealing with datetime instances
s.apply(lambda v: v.timestamp())

If you use python 3.x. You can get date with time in seconds from 1/1/1970 00:00
from datetime import datetime
dt = datetime.today() # Get timezone naive now
seconds = dt.timestamp()

Related

Python ,Duration Calcution between Timestamps

I'm working on backend ,Short Explanation :
I have 2 timestamps which are in this format "2022-10-29T16:30:00+05:30","2022-10-29T17:30:00+05:30" .I need to calculate this duration between these but I tried to figure out the format of this timestamp,so I could calculate using datetime method in python.
This uses the method datetime.fromisoformat(date_string) to convert the ISO 8601-formatted string into a datetime object. From there, you can subtract to find the time difference. Additionally, you may want to add some code to check for negative results, or you can simply use the function abs(x).
import datetime
def duration_between(ts_1: str, ts_2: str) -> datetime.datetime:
ts_1_dt = datetime.datetime.fromisoformat(ts_1)
ts_2_dt = datetime.datetime.fromisoformat(ts_2)
return ts_2_dt - ts_1_dt
ts_1 = "2022-10-29T16:30:00+05:30"
ts_2 = "2022-10-29T17:30:00+05:30"
delta: datetime.datetime = duration_between(ts_1, ts_2)
print(delta) # 1:00:00
print(delta.total_seconds()) # 3600.0
To obtain the delta in other common formats (years, days, hours, minutes, seconds, microseconds), see this answer: https://stackoverflow.com/a/47207182/11597788

How to Split a substract of a date in python

My code is the following:
date = datetime.datetime.now()- datetime.datetime.now()
print date
h, m , s = str(date).split(':')
When I print h the result is:
-1 day, 23
How do I get only the hour (the 23) from the substract using datetime?
Thanks.
If you subtract the current date from a past date, you would get a negative timedelta value.
You can get the seconds with td.seconds and corresponding hour value via just dividing by 3600.
from datetime import datetime
import time
date1 = datetime.now()
time.sleep(3)
date2 = datetime.now()
# timedelta object
td = date2 - date1
print(td.days, td.seconds // 3600, td.seconds)
# 0 0 3
You're not too far off but you should just ask your question as opposed to a question with a "real scenario" later as those are often two very different questions. That way you get an answer to your actual question.
All that said, rather than going through a lot of hoop-jumping with splitting the datetime object, assigning it to a variable which you then later use look for what you need in, it's better to just know what DateTime can do since that can be such a common part of your coding. You would also do well to look at timedelta (which is part of datetime) and if you use pandas, timestamp.
from datetime import datetime
date = datetime.now()
print(date)
print(date.hour)
I can get you the hour of datetime.datetime.now()
You could try indexing a list of a string of datetime.datetime.now():
print(list(str(datetime.datetime.now()))[11] + list(str(datetime.datetime.now()))[12])
Output (in my case when tested):
09
Hope I am of help!

How to use 24 hour time series data as a predictive feature

I am just wondering how best to approach using this 24 hour time format as a predictive feature. My thoughts were to bin it into 24 categories for each hour of the day. Is there an easy way to convert this object into a python datetime object that would make binning easier or how would you advise handling this feature? Thanks :)
df['Duration']
0 2:50
1 7:25
2 19:00
3 5:25
4 4:45
5 2:25
df['Duration'].dtype
dtype('O')
The best solution will depend on what you hope to get from your model. In many cases it makes sense to convert it to total number of seconds (or minutes or hours) since some epoch. To convert your data to seconds since 00:00, you can use:
from datetime import datetime
t_str = "2:50"
t_delta = datetime.strptime(t_str, "%H:%M") - datetime(1900, 1, 1)
seconds = t_delta.total_seconds()
hours = seconds/60**2
print(seconds)
# 10200.0
Using Python's datetime class will not support time values over 23:59. Since it appears that your data may actually be a duration, you may want to represent it as an instance of Python's timedelta class.
from datetime import timedelta
h, m = map(int, t_str.split(sep=':'))
t_delta = timedelta(hours=h, minutes=m)
# Get total number of seconds
seconds = t_delta.total_seconds()
You can use datetime to create a useable datetime string
>>> from datetime import datetime
>>> x = datetime(2019, 1, 1, 0).strftime('%Y-%m-%d %H:%M:%S')
>>> # Use that for your timestring then you can reverse it nicely back into a datetime object
>>> d = datetime.strptime('2019-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')
Of course you can use any valid format string.
You should calculate the time in seconds or minutes or hours from some initial time like the 1st time. Then you can make an x-y scatter plot of the data since the x-axis (time) is now numbers.

python: convert date timestamp to epoch unix time and figure out number of days remaining?

I want to convert 2014-08-14 20:01:28.242 into a unix timestamp 245293529385 and subtract this by the current timestamp in order to figure out how many days have past and are ultimately remaining by subtracting this value from 14.
Scenario: user signs up and I want to count down the number of days remaining in their trial.
time.strptime to the rescue! Use the format string %Y-%m-%d %H:%M:%S.%f. For example:
import time
t = '2014-08-14 20:01:28.242'
ts = time.strptime(t, '%Y-%m-%d %H:%M:%S.%f')
timestamp = time.mktime(ts)
Now to convert it to a datetime (from: How do you convert a Python time.struct_time object into a datetime object? ):
from datetime import datetime
dt = datetime.fromtimestamp(timestamp)
There are two parts:
Convert input time string into datetime object
#!/usr/bin/env python
from datetime import datetime
dt = datetime.strptime('2014-08-14 20:01:28.242', '%Y-%m-%d %H:%M:%S.%f')
Convert datetime object to Unix time ("seconds since epoch")
The result depends on what time zone is used for the input time e.g., if the input is in UTC then the corresponding POSIX timestamp is:
timestamp = (dt - datetime(1970,1,1)).total_seconds()
# -> 1408046488.242
If your input is in the local timezone then see How do I convert local time to UTC in Python?

Converting timestamp with milliseconds to datetime in python

ALL,
I'm trying to get a statistical data of the file. Doing so gives me following:
atime - datetime timestamp representation
atime_nano - nano-seconds resolution in addition to a_time.
What I'd like to do is to convert atime.atime_nano to a datetime variable in Python.
So if I have:
atime = 1092847621L
atime_nano = 7100000L
I'd like to convert it to the datetime object in python that will have correct date with the milliseconds.
How can I do that?
Thank you.
Datetimes can have microseconds (1 microsecond = 1000 nanoseconds)
You can do the following for your example:
dt = datetime.fromtimestamp(1092847621L).replace(microsecond = 7100000L/1000)

Categories

Resources