当前位置:网站首页>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
边栏推荐
- Rew acoustic test (II): offline test
- Flutter theme (skin) changes
- Tutorial for beginners of small programs day01
- Anchorgenerator for mmdet line by line interpretation
- Application of hongruan face recognition
- Opencv learning notes-day14 drawing of image geometry (rect class rotatedrect class, rectangle drawing rectangle circle drawing circular function line drawing line function ellipse drawing elliptic fu
- Deep Learning with Pytorch- A 60 Minute Blitz
- Talking about the difference between kotlin collaboration and thread
- RPC understanding
- Splice and slice functions of JS
猜你喜欢
Duplicate entry '2' for key 'primary appears in JPA‘
Terminal -- Zsh of terminal three swordsmen
Evaluation standard for audio signal quality of intelligent speakers
Dart asynchronous task
Agp7.0|kts makes a reinforced plug-in
12. problem set: process, thread and JNI architecture
Pytorch BERT
Raspberry pie 4B no screen installation system and networking using VNC wireless projection function
[shutter] solve failed assertion: line 5142 POS 12: '_ debugLocked‘: is not true.
Rew acoustic test (III): generate test signal
随机推荐
Couldn't load this key (openssh ssh-2 private key (old PEM format))
Evaluation standard for audio signal quality of intelligent speakers
I once met a girl whom I most wanted to take care of all my life. Later... No later
So the toolbar can still be used like this? The toolbar uses the most complete parsing. Netizen: finally, you don't have to always customize the title bar!
Deep understanding of kotlin collaboration context coroutinecontext
Handwriting sorter component
Introduction to the runner of mmcv
Talk about writing
Torchvision loads the weight of RESNET except the full connection layer
快应用中实现自定义抽屉组件
Express file download
JVM tuning related commands and explanations
Express file upload
Opencv learning notes-day9 opencv's own color table operation (colormap coloraptypes enumeration data types and applycolormap() pseudo color function)
Rew acoustic test (I): microphone calibration
Use of Baidu face recognition API
Esp32 things (x): other functions
Harmonyos actual combat - ten thousand words long article understanding service card development process
Rew acoustic test (III): generate test signal
ES6 learning path (III) deconstruction assignment