Is it possible to manipulate negative time values in Python? - python

Is there a way to generate negative time values in Python?
I want to generate a time range ranging from -4 minutes to a variable positive time (between 5 to 10 min), something like this:
import datetime
import pandas as pd
time_range = range(-datetime.time(minute=4), datetime.time(minute=5))
# or
time_range = pd.date_range(-datetime.time(minute=4), datetime.time(minute=5))
But datetime does not seem to support negative values.
I need it to generate a graph like the following one but with a time/datetime index instead of integer values (A time/datetime index is especially useful on a plotly graph as it gives a readable index at any zoom level)
In addition, I believe that the possibility to generate negative time values could have many other applications.

datetime.time doesn't accept negative values
Maybe you can try to do something with timedelta
from datetime import timedelta
delta = timedelta(minutes=-4)
I hope this clue will help you.
Saying “thanks” is appreciated, but it doesn’t answer the question. Instead, vote up the answers that helped you the most! If these answers were helpful to you, please consider saying thank you in a more constructive way – by contributing your own answers to questions your peers have asked here.

Related

Pandas tz.convert GMT and local time does not match

I am trying to convert UTC data to local time Mozambique. For Mozambique the local time follows GMT+2 or Africa/Maputo. However, when using .tz_localize('UTC').tz_convert(X) where X can either be = 'GMT+2' or = 'Africa/Maputo' I get separate answers. As an example:
import pandas as pd
import numpy as np
np.random.seed(2019)
N = 1000
rng = pd.date_range('2019-01-01', freq='10Min', periods=N)
df = pd.DataFrame(np.random.rand(N, 3), columns=['temp','depth','acceleration'], index=rng)
print(df.tz_localize('UTC').tz_convert('Etc/GMT+2'))
print(df.tz_localize('UTC').tz_convert('Africa/Maputo'))
The code that solves my problem is: df.tz_localize('UTC').tz_convert('Africa/Maputo'). Therefore, I wonder if I have misunderstood the tz_convert('Etc/GMT+2') method, and why the two different solutions dont provide the same answers. tz_convert('Etc/GMT-2') solves the trick but is not intuitive, at least to me.
Thanks in advance.
The time zone conversion using etcetera works in reverse, and perhaps it should be deprecated altogether, considering the following observation on its documentation:
These entries are mostly present for historical reasons, so that
people in areas not otherwise covered by the tz files could "zic -l"
to a time zone that was right for their area. These days, the
tz files cover almost all the inhabited world, so there's little
need now for the entries that are not on UTC.
Your workaround is correct and the best explanation why can be found here. Maybe stick with the tz_convert('Africa/Maputo').

Create a pseudo random number from microsecond

I'm starting to learn python now, so I'm sorry if it's a stupid question, but I couldn't figure it out or find another question like this. When I write
import datetime
datetime.datetime.now()
It generates a tuple, at least I suppose so because it's between parentesis (). I wanted to separate them in a list using .split(',') and then get the last number on the microsecond which would be a pseudo random number. Can anyone help me?
I solved my problem, I didn't knew there was a documetation explaining the classes! Thank you all for helping me! Here is how I solved it
import datetime
aee=datetime.datetime.isoformat(datetime.datetime.now())
aee=aee[-1]
print(aee)
Here is simple solution. Does that meet your expectations?
import datetime
import math
# This prints microseconds of current time
print(datetime.datetime.now().microsecond)
# This is used to extract milliseconds
print(math.floor(datetime.datetime.now().microsecond / 1000))

Apply a function to each row python

I am trying to convert from UTC time to LocaleTime in my dataframe. I have a dictionary where I store the number of hours I need to shift for each country code. So for example if I have df['CountryCode'][0]='AU' and I have a df['UTCTime'][0]=2016-08-12 08:01:00 I want to get df['LocaleTime'][0]=2016-08-12 19:01:00 which is
df['UTCTime'][0]+datetime.timedelta(hours=dateDic[df['CountryCode'][0]])
I have tried to do it with a for loop but since I have more than 1 million rows it's not efficient. I have looked into the apply function but I can't seem to be able to put it to take inputs from two different columns.
Can anyone help me?
Without having a more concrete example its difficult but try this:
pd.to_timedelta(df.CountryCode.map(dateDict), 'h') + df.UTCTime

How to remove day from datetime index in pandas?

The idea behind this question is, that when I'm working with full datetime tags and data from different days, I sometimes want to compare how the hourly behavior compares.
But because the days are different, I can not directly plot two 1-hour data sets on top of each other.
My naive idea would be that I need to remove the day from the datetime index on both sets and then plot them on top of each other. What's the best way to do that?
Or, alternatively, what's the better approach to my problem?
This may not be exactly it but should help you along, assuming ts is your timeseries:
hourly = ts.resample('H')
hourly.index = pd.MultiIndex.from_arrays([hourly.index.hour, hourly.index.normalize()])
hourly.unstack().plot()
If you don't care about the day AT ALL, just hourly.index = hourly.index.hour should work

Comparing DateOffsets in pandas

Is there a way to compare the size of two DateOffset objects?
>>> from pandas.core.datetools import *
>>> Hour(24) > Minute(5)
False
This works with timedelta, so I assumed that pandas would inherit that behavior - or is the time system made from scratch?
pandas DateOffsets does not inherit from timedelta. It's possible for some DateOffsets to be compared, but for offsets like MonthEnd, MonthStart, etc, the span of time to the next offset is non-uniform and depends on the starting date.
Please feel free to start a github issue on this at https://github.com/pydata/pandas, we can continue the discussion there and it'll serve as a reminder.
Thanks.

Categories