Rookie question:
the following works:
import time
# create time
dztupel = 1971, 1, 1, 0, 0, 1, 0, 0, 0
print(time.strftime("%d.%m.%Y %H:%M:%S", dztupel))
damals = time.mktime(dztupel)
# output
lt = time.localtime(damals)
wtage = ["Montag", "Dienstag", "Mittwoch","Donnerstag","Freitag","Samstag", "Sonntag"]
wtagnr = lt[6]
print("Das ist ein", wtage[wtagnr])
tag_des_jahres = lt[7]
print("Der {0:d}. Tag des Jahres".format(tag_des_jahres))
but:
dztupel = 1970, 1, 1, 0, 0, 1, 0, 0, 0
does not work,at least not at windows 10. edit: I get out of range error.
But time should start at January 1st 1970 at 0 hour 0 min and 0 seconds. shouldn't it ?
In your second snippet, check out what the time.mktime() function returns, given that dztupel represents a datetime of 11:01am UTC on 1/1/1969 (shows as one hour ahead because of BST (i.e., UTC+0100) locally on my system):
>>> import time
>>> dztupel = 1970, 1, 1, 0, 0, 1, 0, 0, 0 # In BST locally for me, remember, so one hour less seconds than printed EPOCH seconds
>>> time.mktime(dztupel) # This command
-3599.0 # seconds after (i.e., before as is negative) 1/1/1970 UTC0000
It's negative because EPOCH time (which time.mktike is printing, in seconds) starts at UTC midnight on 1/1/1970:
>>> dztupel = 1970, 1, 1, 1, 0, 0, 0, 0, 0 # 1/1/1970 BST0100 == 1/1/1970 UTC0000
>>> time.mktime(dztupel)
0.0 # seconds after 1/1/1970 UTC0000
Hence 0.0, as it's 0 seconds since dztupel = 1970, 1, 1, 1, 0, 0, 0, 0, 0 since BST 0100 on 1/1/1970, or since UTC midnight on 1/1/1970.
Really, we want to print as UTC, so instead of time.localtime(), use time.gmtime():
>>> dztupel = 1970, 1, 1, 0, 0, 1, 0, 0, 0
>>> time.gmtime(time.mktime(dztupel))
time.struct_time(tm_year=1969, tm_mon=12, tm_mday=31, tm_hour=23, tm_min=0, tm_sec=1, tm_wday=2, tm_yday=365, tm_isdst=0)
Then use strftime() to format it:
>>> gmt = time.gmtime(time.mktime(dztupel))
>>> time.strftime('%Y-%m-%d %H:%M:%S', gmt)
'1969-12-31 23:00:01'
Related
time range like this
strart_date_time = datetime(2021, 1, 1, 5, 00, 00)
end_date_time = datetime(2021,1, 3, 00,00,00)
I want Output Like This I mean I want every single second count between given time range hope you understand.....
ThankYou in advance
output-
2021, 1, 1, 0, 00, 01
2021, 1, 1, 0, 01, 02
2021, 1, 1, 2, 30, 03
...
You can get the time difference in seconds, loop and display new date at each second
from datetime import datetime, timedelta
start_date_time = datetime(2021, 1, 1, 5, 00, 00)
end_date_time = datetime(2021,1, 3, 00,00,00)
time_diff = int((end_date_time - start_date_time).total_seconds())
for i in range(time_diff):
print(start_date_time + timedelta(0, i))
I have the following DataFrame:
import pandas as pd
data = {'ID': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
'Time_order': ['2019-01-01 07:00:00', '2019-01-01 07:25:00', '2019-01-02 07:02:00', '2019-01-02 07:27:00', '2019-01-02 06:58:00', '2019-01-03 07:24:00', '2019-01-04 07:03:00', '2019-01-04 07:24:00', '2019-01-05 07:05:00', '2019-01-05 07:30:00', '2019-01-06 07:00:00', '2019-01-06 07:25:00', '2019-01-07 07:02:00', '2019-01-07 07:27:00', '2019-01-08 06:58:00', '2019-01-08 07:24:00', '2019-01-09 07:03:00', '2019-01-09 07:24:00', '2019-01-10 07:05:00', '2019-01-10 07:30:00',
'2019-01-11 017:00:00', '2019-01-11 17:25:00', '2019-01-12 07:02:00', '2019-01-12 07:27:00', '2019-01-13 06:58:00', '2019-01-13 07:24:00', '2019-01-14 07:03:00', '2019-01-14 07:24:00', '2019-01-15 07:05:00', '2019-01-15 07:30:00']}
df = pd.DataFrame(data)
df['Time_order'] = pd.to_datetime(df['Time_order'])
df['hour'] = df['Time_order'].dt.strftime('%H:%M:%S)
I wanted to make a time_period = 25 minutes of length 25 minutes, so that I can check wether there are orders in that time_period. For example: I will start checking everyday starting from midnight, e.g. from 00:00:00 to 00:25:00 and claculate how many orders are in that order and then move on by a 5 minutes, e.g. from 00:05:00 to 00:30:00 and so on scanning the whole day until 23:59:00. What I am expecting is how many orders where made and pick the maximum ones, so that it returns at which time there is a peak of orders during that time period.
I tired the following:
x = 12 * 24 # each five minutes per hour (12) times 24 hours (a day)
for i in range(x):
df[f'each{i}_minutes_start'] = pd.to_datetime(df['Time_order']).dt.floor(f'{i}_min')
df[f'each{i}_minutes_end'] = df[f'each{i}_minutes_start'] + pd.Timedelta(minutes = 5)
df['time_period'] = df[f'each{i}_minutes_start'].dt.strftime('%H:%M:S%') + '-' + pd.to_datetime(df[f'each{i}_minutes_end']).dt.strtime('%H:%M:S%')
at this point I stucked and could not come forward. Thank you in advance
I think this works:
df.set_index('Time_order').resample("5min").count().rolling(6)['ID'].sum()
I have to search date 1/1/2012 in a data frame using a for loop and I get the corresponding rates. However my date is in a format of datetime.datetime(2012, 1, 1, 0, 0). So automatically the condition to match the date is failing.
Start Date End Date RPI Amount
1/1/1987 31/01/1987 100.0
2/1/1987 28/02/1987 100.4
3/1/1987 31/03/1987 100.6
4/1/1987 30/04/1987 101.8
5/1/1987 31/05/1987 101.9
6/1/1987 30/06/1987 101.9
7/1/1987 31/07/1987 101.8
8/1/1987 31/08/1987 102.1
9/1/1987 30/09/1987 102.4
10/1/1987 31/10/1987 102.9
11/1/1987 30/11/1987 103.4
12/1/1987 31/12/1987 103.3
1/1/1988 31/01/1988 103.3
I have used a for loop to iterate over data frame and then tried to match the date with data frame date. However as the format not matches I am getting result as "NA"
rpi_index_start_date=datetime.strptime(f"{temp_month}/1/{temp_year}","%m/%d/%Y")
temp_year2=rpi_index_start_date.year+1
temp_month2=temp_month
temp_day2=temp_day
#RPI index end date calculation
rpi_index_end_date=datetime.strptime(f"{temp_month2}/{temp_day2}/{temp_year2}","%m/%d/%Y")
for i,row in rpi_rates_df.iterrows():
if rpi_index_start_date==rpi_rates_df.loc[i,"Start Date"]:
index_start_rpi=rpi_rates_df.loc[i,"RPI Amount"]
else:
index_start_rpi="NA"
I have to convert datetime.datetime(2012, 1, 1, 0, 0) in 1/1/2012 format to search in the dataframe.
I expect the output 238 corresponding to 1/1/2012, but the actual output is NA.
To remove the leading zeros on the month and day
For those that use windows:
from datetime import datetime
datetime(2012, 1, 1, 0, 0).strftime("#%m/#%d/%Y")
For those that do not use windows:
from datetime import datetime
datetime(2012, 1, 1, 0, 0).strftime("-%m/-%d/%Y")
Use strftime:
import datetime
datetime.datetime(2012, 1, 1, 0, 0).strftime("%d-%m-%Y")
output:
01-01-2012'
Why do these two lines produce different results?
>>> import pytz
>>> from datetime import datetime
>>> local_tz = pytz.timezone("America/Los_Angeles")
>>> d1 = local_tz.localize(datetime(2015, 8, 1, 0, 0, 0, 0)) # line 1
>>> d2 = datetime(2015, 8, 1, 0, 0, 0, 0, local_tz) # line 2
>>> d1 == d2
False
What's the reason for the difference, and which should I use to localize a datetime?
When you create d2 = datetime(2015, 8, 1, 0, 0, 0, 0, local_tz), it does not handle daylight saving time (DST) correctly. local_tz.localize() does.
d1 is
>>> local_tz.localize(datetime(2015, 8, 1, 0, 0, 0, 0))
datetime.datetime(
2015, 8, 1, 0, 0,
tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>
)
d2 is
>>> datetime(2015, 8, 1, 0, 0, 0, 0, local_tz)
datetime.datetime(
2015, 8, 1, 0, 0,
tzinfo=<DstTzInfo 'America/Los_Angeles' LMT-1 day, 16:07:00 STD>
)
You can see that they are not representing the same time.
d2 way is fine if you are going to work with UTC. UTC does not have daylight saving time (DST) transitions to deal with.
The correct way to handle timezone is to use local_tz.localize() to support daylight saving time (DST)
More information and additional examples can be found here:
http://pytz.sourceforge.net/#localized-times-and-date-arithmetic
I have following unsorted dict (dates are keys):
{"23-09-2014": 0, "11-10-2014": 0, "30-09-2014": 0, "26-09-2014": 0,
"03-10-2014": 0, "19-10-2014": 0, "15-10-2014": 0, "22-09-2014": 0,
"17-10-2014": 0, "29-09-2014": 0, "13-10-2014": 0, "16-10-2014": 0,
"12-10-2014": 0, "25-09-2014": 0, "14-10-2014": 0, "08-10-2014": 0,
"02-10-2014": 0, "09-10-2014": 0, "18-10-2014": 0, "24-09-2014": 0,
"28-09-2014": 0, "10-10-2014": 0, "21-10-2014": 0, "20-10-2014": 0,
"06-10-2014": 0, "04-10-2014": 0, "27-09-2014": 0, "05-10-2014": 0,
"01-10-2014": 0, "07-10-2014": 0}
I am trying to sort it from oldest to newest.
I've tried code:
mydict = OrderedDict(sorted(mydict .items(), key=lambda t: t[0], reverse=True))
to sort it, and it almost worked. It produced sorted dict, but it has ignored months:
{"01-10-2014": 0, "02-10-2014": 0, "03-10-2014": 0, "04-10-2014": 0,
"05-10-2014": 0, "06-10-2014": 0, "07-10-2014": 0, "08-10-2014": 0,
"09-10-2014": 0, "10-10-2014": 0, "11-10-2014": 0, "12-10-2014": 0,
"13-10-2014": 0, "14-10-2014": 0, "15-10-2014": 0, "16-10-2014": 0,
"17-10-2014": 0, "18-10-2014": 0, "19-10-2014": 0, "20-10-2014": 0,
"21-10-2014": 0, "22-09-2014": 0, "23-09-2014": 0, "24-09-2014": 0,
"25-09-2014": 0, "26-09-2014": 0, "27-09-2014": 0, "28-09-2014": 0,
"29-09-2014": 0, "30-09-2014": 0}
How can I fix this?
EDIT:
I need this to count objects created in django application in past X days, for each day.
event_chart = {}
date_list = [datetime.datetime.today() - datetime.timedelta(days=x) for x in range(0, 30)]
for date in date_list:
event_chart[formats.date_format(date, "SHORT_DATE_FORMAT")] = Event.objects.filter(project=project_name, created=date).count()
event_chart = OrderedDict(sorted(event_chart.items(), key=lambda t: t[0]))
return HttpResponse(json.dumps(event_chart))
You can use the datetime module to parse the strings into actual dates:
>>> from datetime import datetime
>>> sorted(mydict .items(), key=lambda t:datetime.strptime(t[0], '%d-%m-%Y'), reverse=True)
If you want to create a json response in the format: {"22-09-2014": 0, 23-09-2014": 0, "localized date": count_for_that_date} so that oldest dates will appear earlier in the output then you could make event_chart an OrderedDict:
event_chart = OrderedDict()
today = DT.date.today() # use DT.datetime.combine(date, DT.time()) if needed
for day in range(29, -1, -1): # last 30 days
date = today - DT.timedelta(days=day)
localized_date = formats.date_format(date, "SHORT_DATE_FORMAT")
day_count = Event.objects.filter(project=name, created=date).count()
event_chart[localized_date] = day_count
return HttpResponse(json.dumps(event_chart))