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

1import six 

2import datetime 

3 

4 

5# There might be a better way to get the epoch with tzinfo, please create 

6# a pull request if you know a better way that functions for Python 2 and 3 

7epoch = datetime.datetime(year=1970, month=1, day=1) 

8 

9 

10def timedelta_to_seconds(delta): 

11 '''Convert a timedelta to seconds with the microseconds as fraction 

12 

13 Note that this method has become largely obsolete with the 

14 `timedelta.total_seconds()` method introduced in Python 2.7. 

15 

16 >>> from datetime import timedelta 

17 >>> '%d' % timedelta_to_seconds(timedelta(days=1)) 

18 '86400' 

19 >>> '%d' % timedelta_to_seconds(timedelta(seconds=1)) 

20 '1' 

21 >>> '%.6f' % timedelta_to_seconds(timedelta(seconds=1, microseconds=1)) 

22 '1.000001' 

23 >>> '%.6f' % timedelta_to_seconds(timedelta(microseconds=1)) 

24 '0.000001' 

25 ''' 

26 # Only convert to float if needed 

27 if delta.microseconds: 

28 total = delta.microseconds * 1e-6 

29 else: 

30 total = 0 

31 total += delta.seconds 

32 total += delta.days * 60 * 60 * 24 

33 return total 

34 

35 

36def format_time(timestamp, precision=datetime.timedelta(seconds=1)): 

37 '''Formats timedelta/datetime/seconds 

38 

39 >>> format_time('1') 

40 '0:00:01' 

41 >>> format_time(1.234) 

42 '0:00:01' 

43 >>> format_time(1) 

44 '0:00:01' 

45 >>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6)) 

46 '2000-01-02 03:04:05' 

47 >>> format_time(datetime.date(2000, 1, 2)) 

48 '2000-01-02' 

49 >>> format_time(datetime.timedelta(seconds=3661)) 

50 '1:01:01' 

51 >>> format_time(None) 

52 '--:--:--' 

53 >>> format_time(format_time) # doctest: +ELLIPSIS 

54 Traceback (most recent call last): 

55 ... 

56 TypeError: Unknown type ... 

57 

58 ''' 

59 precision_seconds = precision.total_seconds() 

60 

61 if isinstance(timestamp, six.string_types + six.integer_types + (float, )): 

62 try: 

63 castfunc = six.integer_types[-1] 

64 timestamp = datetime.timedelta(seconds=castfunc(timestamp)) 

65 except OverflowError: # pragma: no cover 

66 timestamp = None 

67 

68 if isinstance(timestamp, datetime.timedelta): 

69 seconds = timestamp.total_seconds() 

70 # Truncate the number to the given precision 

71 seconds = seconds - (seconds % precision_seconds) 

72 

73 return str(datetime.timedelta(seconds=seconds)) 

74 elif isinstance(timestamp, datetime.datetime): # pragma: no cover 

75 # Python 2 doesn't have the timestamp method 

76 if hasattr(timestamp, 'timestamp'): 

77 seconds = timestamp.timestamp() 

78 else: 

79 seconds = timedelta_to_seconds(timestamp - epoch) 

80 

81 # Truncate the number to the given precision 

82 seconds = seconds - (seconds % precision_seconds) 

83 

84 try: # pragma: no cover 

85 if six.PY3: 

86 dt = datetime.datetime.fromtimestamp(seconds) 

87 else: 

88 dt = datetime.datetime.utcfromtimestamp(seconds) 

89 except ValueError: # pragma: no cover 

90 dt = datetime.datetime.max 

91 return str(dt) 

92 elif isinstance(timestamp, datetime.date): 

93 return str(timestamp) 

94 elif timestamp is None: 

95 return '--:--:--' 

96 else: 

97 raise TypeError('Unknown type %s: %r' % (type(timestamp), timestamp))