Coverage for ibllib/time.py: 97%

31 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-10-11 11:13 +0100

1# library of small functions 

2import datetime 

3import numpy as np 

4 

5 

6def isostr2date(isostr): 

7 """ 

8 Convert strings representing dates into datetime.datetime objects aimed ad Django REST API 

9 ISO 8601: '2018-05-22T14:35:22.99585' or '2018-05-22T14:35:22' 

10 

11 :param isostr: a string, list of strings or panda Series / numpy arrays containing strings 

12 :return: a scalar, list of 

13 """ 

14 # NB this is intended for scalars or small list. See the ciso8601 pypi module instead for 

15 # a performance implementation 

16 if not isinstance(isostr, str): 1uvwdbxyzaA

17 return [isostr2date(el) for el in isostr] 1d

18 

19 format = '%Y-%m-%dT%H:%M:%S' 1uvwdbxyzaA

20 if '.' in isostr: 1uvwdbxyzaA

21 format += '.%f' 1uvwdbxyzaA

22 if '+' in isostr: 1uvwdbxyzaA

23 format += '.%f' 

24 return datetime.datetime.strptime(isostr, format) 1uvwdbxyzaA

25 

26 

27def date2isostr(adate): 

28 # NB this is intended for scalars or small list. See the ciso8601 pypi module instead for 

29 # a performance implementation 

30 if type(adate) is datetime.date: 1Ca

31 adate = datetime.datetime.fromordinal(adate.toordinal()) 1C

32 return datetime.datetime.isoformat(adate) 1Ca

33 

34 

35def format_date_range(date_range): 

36 if all([isinstance(d, str) for d in date_range]): 1B

37 date_range = [datetime.datetime.strptime(d, '%Y-%m-%d') for d in date_range] 1B

38 elif not all([isinstance(d, datetime.date) for d in date_range]): 1B

39 raise ValueError('Date range doesn''t have proper format: list of 2 strings "yyyy-mm-dd" ') 1B

40 # the django filter is implemented in datetime and assumes the beginning of the day (last day 

41 # is excluded by default 

42 date_range = [d.strftime('%Y-%m-%d') for d in date_range] 1B

43 return date_range 1B

44 

45 

46def convert_pgts(time): 

47 """Convert PointGray cameras timestamps to seconds. 

48 Use convert then uncycle""" 

49 # offset = time & 0xFFF 

50 cycle1 = (time >> 12) & 0x1FFF 1efghbijklmnopqrsta

51 cycle2 = (time >> 25) & 0x7F 1efghbijklmnopqrsta

52 seconds = cycle2 + cycle1 / 8000. 1efghbijklmnopqrsta

53 return seconds 1efghbijklmnopqrsta

54 

55 

56def uncycle_pgts(time): 

57 """Unwrap the converted seconds of a PointGray camera timestamp series.""" 

58 cycles = np.insert(np.diff(time) < 0, 0, False) 1efghbijklmnopqrsta

59 cycleindex = np.cumsum(cycles) 1efghbijklmnopqrsta

60 return time + cycleindex * 128 1efghbijklmnopqrsta