当前位置:网站首页>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
边栏推荐
- Installation, use and explanation of vulnerability scanning tool OpenVAS
- [protobuf] protobuf generates cc/h file through proto file
- Design specification for smart speakers v1.0
- Coredata acquisition in swift sorting, ascending, descending
- Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)
- Experience of an acmer
- Niuke walks on the tree (ingenious application of parallel search)
- Talk about the kotlin cooperation process and the difference between job and supervisorjob
- Rew acoustic test (III): generate test signal
- POJ 1753 flip game (DFS 𞓜 bit operation)
猜你喜欢
Small program learning path 1 - getting to know small programs
快应用中实现自定义抽屉组件
Opencv learning notes -day10 logical operation of image pixels (usage of rectangle function and rect function and bit related operation in openCV)
Opencv learning notes -day8 (keyboard typing (waitkey()); Wait for typing) action: triggers some action when the appropriate character is typed using the keyboard)
Rew acoustic test (I): microphone calibration
Express get request
C accesses mongodb and performs CRUD operations
Opencv learning notes -day 11 (split() channel separation function and merge() channel merge function)
Advanced technology management -- how managers design and build echelons
Opencv learning notes-day6-7 (scroll bar operation demonstration is used to adjust image brightness and contrast, and createtrackbar() creates a scroll bar function)
随机推荐
Esp32 things (I): Preface
Dart basic notes
Niuke rearrangement rule taking method
Based on svelte3 X desktop UI component library svelte UI
Duplicate entry '2' for key 'primary appears in JPA‘
How do I start? (continuously updating)
8.8 heap insertion and deletion
Code management related issues
Challenge transform() 2D
Esp32 things (VIII): music playing function of function development
Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)
Bottomsheetbehavior principle of realizing the home page effect of Gaode map
快应用中实现自定义抽屉组件
Raspberry pie 4B no screen installation system and networking using VNC wireless projection function
Unsupportedclassversionerror is reported when starting jar package. How to repair it
4. use ibinder interface flexibly for short-range communication
Opencv learning notes -day10 logical operation of image pixels (usage of rectangle function and rect function and bit related operation in openCV)
Esp32 things (3): overview of the overall system design
Deep Learning with Pytorch- A 60 Minute Blitz
What are the SQL add / delete / modify queries?