当前位置:网站首页>Numpy (time date and time increment)
Numpy (time date and time increment)
2022-06-30 09:26:00 【Orangejuicer】
datetime64 Basics
stay numpy in , We can easily convert a string to a time date type datetime64(datetime Has been python Occupied by the included date time library ).
datatime64 Is a date time type with units , Its units are as follows :

【 example 】 Create from a string datetime64 Type , By default ,numpy The corresponding unit will be automatically selected according to the string .
import numpy as np
a = np.datetime64('2020-03-01')
print(a, a.dtype) # 2020-03-01 datetime64[D]
a = np.datetime64('2020-03')
print(a, a.dtype) # 2020-03 datetime64[M]
a = np.datetime64('2020-03-08 20:00:05')
print(a, a.dtype) # 2020-03-08T20:00:05 datetime64[s]
a = np.datetime64('2020-03-08 20:00')
print(a, a.dtype) # 2020-03-08T20:00 datetime64[m]
a = np.datetime64('2020-03-08 20')
print(a, a.dtype) # 2020-03-08T20 datetime64[h]
【 example 】 Create from a string datetime64 Type , You can force the units to be used .
import numpy as np
a = np.datetime64('2020-03', 'D')
print(a, a.dtype) # 2020-03-01 datetime64[D]
a = np.datetime64('2020-03', 'Y')
print(a, a.dtype) # 2020 datetime64[Y]
print(np.datetime64('2020-03') == np.datetime64('2020-03-01')) # True
print(np.datetime64('2020-03') == np.datetime64('2020-03-02')) #False
As can be seen from the above example ,2020-03 and 2020-03-01 It means the same time . in fact , If two datetime64 Objects have different units , They may still represent the same moment . And from the larger units ( Such as month ) Convert to smaller units ( Such as days ) Is safe .
【 example 】 Create from a string datetime64 Array time , If the units are not uniform , Then it will all be converted into the smallest unit .
import numpy as np
a = np.array(['2020-03', '2020-03-08', '2020-03-08 20:00'], dtype='datetime64')
print(a, a.dtype)
# ['2020-03-01T00:00' '2020-03-08T00:00' '2020-03-08T20:00'] datetime64[m]
【 example 】 Use arange() establish datetime64 Array , Used to generate date range .
import numpy as np
a = np.arange('2020-08-01', '2020-08-10', dtype=np.datetime64)
print(a)
# ['2020-08-01' '2020-08-02' '2020-08-03' '2020-08-04' '2020-08-05'
# '2020-08-06' '2020-08-07' '2020-08-08' '2020-08-09']
print(a.dtype) # datetime64[D]
a = np.arange('2020-08-01 20:00', '2020-08-10', dtype=np.datetime64)
print(a)
# ['2020-08-01T20:00' '2020-08-01T20:01' '2020-08-01T20:02' ...
# '2020-08-09T23:57' '2020-08-09T23:58' '2020-08-09T23:59']
print(a.dtype) # datetime64[m]
a = np.arange('2020-05', '2020-12', dtype=np.datetime64)
print(a)
# ['2020-05' '2020-06' '2020-07' '2020-08' '2020-09' '2020-10' '2020-11']
print(a.dtype) # datetime64[M]
datetime64 and timedelta64 operation
【 example 】timedelta64 Two datetime64 The difference between .timedelta64 Also with units , And two of the sum and subtraction operations datetime64 The smaller units in the .
import numpy as np
a = np.datetime64('2020-03-08') - np.datetime64('2020-03-07')
b = np.datetime64('2020-03-08') - np.datetime64('202-03-07 08:00')
c = np.datetime64('2020-03-08') - np.datetime64('2020-03-07 23:00', 'D')
print(a, a.dtype) # 1 days timedelta64[D]
print(b, b.dtype) # 956178240 minutes timedelta64[m]
print(c, c.dtype) # 1 days timedelta64[D]
a = np.datetime64('2020-03') + np.timedelta64(20, 'D')
b = np.datetime64('2020-06-15 00:00') + np.timedelta64(12, 'h')
print(a, a.dtype) # 2020-03-21 datetime64[D]
print(b, b.dtype) # 2020-06-15T12:00 datetime64[m]
【 example 】 Generate timedelta64 when , Pay attention to the year (‘Y’) He Yue (‘M’) These two units cannot operate with other units ( How many days a year ? There are several hours in a month ? These are all uncertain ).
import numpy as np
a = np.timedelta64(1, 'Y')
b = np.timedelta64(a, 'M')
print(a) # 1 years
print(b) # 12 months
c = np.timedelta64(1, 'h')
d = np.timedelta64(c, 'm')
print(c) # 1 hours
print(d) # 60 minutes
print(np.timedelta64(a, 'D'))
# TypeError: Cannot cast NumPy timedelta64 scalar from metadata [Y]
# to [D] according to the rule 'same_kind'
print(np.timedelta64(b, 'D'))
# TypeError: Cannot cast NumPy timedelta64 scalar from metadata [M]
# to [D] according to the rule 'same_kind'
【 example 】timedelta64 Arithmetic .
import numpy as np
a = np.timedelta64(1, 'Y')
b = np.timedelta64(6, 'M')
c = np.timedelta64(1, 'W')
d = np.timedelta64(1, 'D')
e = np.timedelta64(10, 'D')
print(a) # 1 years
print(b) # 6 months
print(a + b) # 18 months
print(a - b) # 6 months
print(2 * a) # 2 years
print(a / b) # 2.0
print(c / d) # 7.0
print(c % e) # 7 days
【 example 】numpy.datetime64 And datetime.datetime transformation
import numpy as np
import datetime
dt = datetime.datetime(year=2020, month=6, day=1, hour=20, minute=5, second=30)
dt64 = np.datetime64(dt, 's')
print(dt64, dt64.dtype)
# 2020-06-01T20:05:30 datetime64[s]
dt2 = dt64.astype(datetime.datetime)
print(dt2, type(dt2))
# 2020-06-01 20:05:30 <class 'datetime.datetime'>
datetime64 Application
To allow datetime to be used in a context where only certain days of the week are valid ,NumPy Contains a set of “busday”( Working day ) function .
numpy.busday_offset(dates, offsets, roll=‘raise’, weekmask=‘1111100’,holidays=None, busdaycal=None, out=None)
First, adjust the date to belong to the effective date according to the rolling rule , The offset is then applied to the given date calculated in the effective date .
Parameters roll:{‘raise’, ‘nat’, ‘forward’, ‘following’, ‘backward’, ‘preceding’, ‘modifiedfollowing’, ‘modifiedpreceding’}
- ‘raise’ means to raise an exception for an invalid day.
- ‘nat’ means to return a NaT (not-a-time) for an invalid day.
- ‘forward’ and ‘following’ mean to take the first valid day later in
time. - ‘backward’ and ‘preceding’ mean to take the first valid day earlier
in time.
【 example 】 Applies the specified offset to the working day , Unit day (‘D’). Calculate the next working day , If the current date is not a working day , Default error . You can specify forward or backward Rules to avoid error reporting .( One is to take the first valid working day forward , One is to take back the first valid working day )
import numpy as np
# 2020-07-10 Friday
a = np.busday_offset('2020-07-10', offsets=1)
print(a) # 2020-07-13
a = np.busday_offset('2020-07-11', offsets=1)
print(a)
# ValueError: Non-business day date in busday_offset
a = np.busday_offset('2020-07-11', offsets=0, roll='forward')
b = np.busday_offset('2020-07-11', offsets=0, roll='backward')
print(a) # 2020-07-13
print(b) # 2020-07-10
a = np.busday_offset('2020-07-11', offsets=1, roll='forward')
b = np.busday_offset('2020-07-11', offsets=1, roll='backward')
print(a) # 2020-07-14
print(b) # 2020-07-13
You can specify an offset of 0 To get the most recent working day forward or backward of the current date , Of course , If the current date itself is a working day , The current date is returned directly .
- numpy.is_busday(dates, weekmask=‘1111100’, holidays=None,busdaycal=None, out=None) Calculates which of the given dates are valid days, and which are not.
【 example 】 Returns whether the specified date is a working day .
import numpy as np
# 2020-07-10 Friday
a = np.is_busday('2020-07-10')
b = np.is_busday('2020-07-11')
print(a) # True
print(b) # False
【 example 】 Count one datetime64[D] Number of working days in the array .
import numpy as np
# 2020-07-10 Friday
begindates = np.datetime64('2020-07-10')
enddates = np.datetime64('2020-07-20')
a = np.arange(begindates, enddates, dtype='datetime64')
b = np.count_nonzero(np.is_busday(a))
print(a)
# ['2020-07-10' '2020-07-11' '2020-07-12' '2020-07-13' '2020-07-14'
# '2020-07-15' '2020-07-16' '2020-07-17' '2020-07-18' '2020-07-19']
print(b) # 6
【 example 】 Custom week mask value , That is, specify which weeks of the week are working days .
import numpy as np
# 2020-07-10 Friday
a = np.is_busday('2020-07-10', weekmask=[1, 1, 1, 1, 1, 0, 0])
b = np.is_busday('2020-07-10', weekmask=[1, 1, 1, 1, 0, 0, 1])
print(a) # True
print(b) # False
- numpy.busday_count(begindates, enddates,weekmask=‘1111100’,holidays=[], busdaycal=None,out=None)Counts the number of valid days between begindates and enddates, not including the day of enddates.
【 example 】 Returns the number of working days between two dates .
import numpy as np
# 2020-07-10 Friday
begindates = np.datetime64('2020-07-10')
enddates = np.datetime64('2020-07-20')
a = np.busday_count(begindates, enddates)
b = np.busday_count(enddates, begindates)
print(a) # 6
print(b) # -6
边栏推荐
- Research on lg1403 divisor
- 使用华为性能管理服务,按需配置采样率
- Opencv learning notes -day13 pixel value statistics calculation of maximum and minimum values, average values and standard deviations (use of minmaxloc() and meanstddev() functions)
- Rew acoustic test (V): equipment required for test
- Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)
- Guilin robust medical acquired 100% equity of Guilin Latex to fill the blank of latex product line
- Set, map and modularity
- Rew acoustic test (I): microphone calibration
- Anchorgenerator for mmdet line by line interpretation
- I'm late for school
猜你喜欢

AutoUpdater. Net client custom update file

Express の post request

I once met a girl whom I most wanted to take care of all my life. Later... No later

Evaluation standard for audio signal quality of intelligent speakers

C accesses mongodb and performs CRUD operations
![[wechat applet] realize applet pull-down refresh and pull-up loading](/img/23/2668a3a36fd46f63732c753fd6f237.jpg)
[wechat applet] realize applet pull-down refresh and pull-up loading

Opencv learning notes -day10 logical operation of image pixels (usage of rectangle function and rect function and bit related operation in openCV)
![[shutter] solve failed assertion: line 5142 POS 12: '_ debugLocked‘: is not true.](/img/77/eb66ec83b34c251e732d495fbaa951.jpg)
[shutter] solve failed assertion: line 5142 POS 12: '_ debugLocked‘: is not true.

Pytorch BERT

Abstract factory pattern
随机推荐
Application of hongruan face recognition
List set export excel table
Rew acoustic test (III): generate test signal
Treatment process record of Union Medical College Hospital (Dongdan hospital area)
[protobuf] protobuf generates cc/h file through proto file
Row column (vertical and horizontal table) conversion of SQL
Metasploit practice - SSH brute force cracking process
Esp32 (4): overview of the overall code architecture
Solution to pychart's failure in importing torch package
Dart asynchronous task
Summary of Android knowledge points and common interview questions
Deep Learning with Pytorch-Train A Classifier
Solution to the sixth training competition of 2020 provincial competition
Code management related issues
How do I start? (continuously updating)
Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)
Get to know handler again
127.0.0.1, 0.0.0.0 and localhost
Sort (simple description)
C # get the current timestamp