Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

''' 

Datatype conversion Tools 

''' 

import datetime 

 

 

class InvalidDateFormat(ValueError): 

'''Custom exception to be thrown when an invalid data format is passed to the to_date function.''' 

pass 

 

 

def to_date(value, date_format='mm/dd/yyyy'): 

''' 

Convert a string to a date. Values that can be processed are: 

dd/mm/yyyy, dd-mm-yyyy, dd.mm.yyyy 

mm/dd/yyyy, mm-dd-yyyy, mm.dd.yyyy 

yyyymmdd 

''' 

value = value.strip() 

value = value.replace('-', '/') 

value = value.replace('.', '/') 

 

# Return None if no value is present. 

if len(value) == 0: 

return None 

 

# Looking for a format of dd/mm/yyyy 

elif date_format == 'dd/mm/yyyy': 

pieces = value.split('/') 

day = int(pieces[0]) 

month = int(pieces[1]) 

year = int(pieces[2]) 

return_date = datetime.date(year, month, day) 

return return_date 

 

# Looking for a format of mm/dd/yyyy 

elif date_format == 'mm/dd/yyyy': 

pieces = value.split('/') 

month = int(pieces[0]) 

day = int(pieces[1]) 

year = int(pieces[2]) 

return_date = datetime.date(year, month, day) 

return return_date 

 

# Looking for a format of yyyymmdd 

elif date_format == 'yyyymmdd': 

year = int(value[0:4]) 

month = int(value[4:6]) 

day = int(value[6:8]) 

return_date = datetime.date(year, month, day) 

return return_date 

 

# If we get this far then the passed in value is in an unknown format. 

else: 

raise InvalidDateFormat('Invalid date format ' + date_format + '.') 

 

 

def to_int(value): 

i = 0 

try: 

i = int(value) 

except Exception: 

i = 0 

return i 

 

 

def to_float(value): 

f = 0 

 

value = value.replace(',', '') 

 

if len(value) < 1: 

return 0 

 

if value[0] == '$': 

value = value[1:] 

 

try: 

f = float(value) 

except Exception: 

f = 0 

return f