or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

filesize-formatting.mdindex.mdinternationalization.mdlist-formatting.mdnumber-formatting.mdtime-formatting.md

time-formatting.mddocs/

0

# Time and Date Formatting

1

2

Natural language time and date formatting utilities that convert datetime objects, timedeltas, and time values into human-readable expressions with support for relative time, precision control, and internationalization.

3

4

## Capabilities

5

6

### Natural Time

7

8

Converts timestamps, datetime objects, or time differences into natural language expressions with automatic tense detection and configurable precision.

9

10

```python { .api }

11

def naturaltime(

12

value: dt.datetime | dt.timedelta | float,

13

future: bool = False,

14

months: bool = True,

15

minimum_unit: str = "seconds",

16

when: dt.datetime | None = None

17

) -> str:

18

"""

19

Return a natural representation of time in human-readable format.

20

21

Args:

22

value: datetime, timedelta, or number of seconds

23

future: Force future tense for numeric inputs (ignored for datetime/timedelta)

24

months: Use months for year calculations (based on 30.5 days)

25

minimum_unit: Lowest unit to display ("seconds", "milliseconds", "microseconds")

26

when: Reference point in time (defaults to current time)

27

28

Returns:

29

Natural time representation with appropriate tense

30

31

Examples:

32

>>> naturaltime(dt.datetime.now() - dt.timedelta(minutes=30))

33

'30 minutes ago'

34

>>> naturaltime(3600, future=True)

35

'an hour from now'

36

>>> naturaltime(dt.datetime.now() + dt.timedelta(days=1))

37

'a day from now'

38

"""

39

```

40

41

### Natural Delta

42

43

Converts time differences into natural language without tense, focusing purely on the duration or time span.

44

45

```python { .api }

46

def naturaldelta(

47

value: dt.timedelta | float,

48

months: bool = True,

49

minimum_unit: str = "seconds"

50

) -> str:

51

"""

52

Return a natural representation of a timedelta without tense.

53

54

Args:

55

value: timedelta or number of seconds

56

months: Use months for calculations between years

57

minimum_unit: Lowest unit to display

58

59

Returns:

60

Natural duration string without tense indicators

61

62

Examples:

63

>>> naturaldelta(dt.timedelta(minutes=30))

64

'30 minutes'

65

>>> naturaldelta(3661)

66

'an hour'

67

>>> naturaldelta(dt.timedelta(days=400))

68

'a year'

69

"""

70

```

71

72

### Natural Day

73

74

Converts dates to natural expressions like "today", "yesterday", "tomorrow", or formatted date strings for other dates.

75

76

```python { .api }

77

def naturalday(value: dt.date | dt.datetime, format: str = "%b %d") -> str:

78

"""

79

Return a natural day representation.

80

81

Args:

82

value: date or datetime object

83

format: strftime format for non-relative dates

84

85

Returns:

86

"today", "yesterday", "tomorrow", or formatted date string

87

88

Examples:

89

>>> naturalday(dt.date.today())

90

'today'

91

>>> naturalday(dt.date.today() - dt.timedelta(days=1))

92

'yesterday'

93

>>> naturalday(dt.date.today() + dt.timedelta(days=1))

94

'tomorrow'

95

"""

96

```

97

98

### Natural Date

99

100

Similar to naturalday but includes the year for dates that are more than approximately five months away from today.

101

102

```python { .api }

103

def naturaldate(value: dt.date | dt.datetime) -> str:

104

"""

105

Like naturalday, but append year for dates >5 months away.

106

107

Args:

108

value: date or datetime object

109

110

Returns:

111

Natural date string with year when appropriate

112

113

Examples:

114

>>> naturaldate(dt.date.today())

115

'today'

116

>>> naturaldate(dt.date(2020, 1, 1)) # if far in past/future

117

'Jan 01 2020'

118

"""

119

```

120

121

### Precise Delta

122

123

Provides precise timedelta representation with multiple units, customizable precision, and the ability to suppress specific units.

124

125

```python { .api }

126

def precisedelta(

127

value: dt.timedelta | float | None,

128

minimum_unit: str = "seconds",

129

suppress: Iterable[str] = (),

130

format: str = "%0.2f"

131

) -> str:

132

"""

133

Return a precise representation of a timedelta.

134

135

Args:

136

value: timedelta, number of seconds, or None

137

minimum_unit: Smallest unit to display

138

suppress: List of units to exclude from output

139

format: Format string for fractional parts

140

141

Returns:

142

Precise multi-unit time representation

143

144

Examples:

145

>>> precisedelta(dt.timedelta(seconds=3633, days=2, microseconds=123000))

146

'2 days, 1 hour and 33.12 seconds'

147

>>> precisedelta(dt.timedelta(seconds=90), suppress=['seconds'])

148

'1.50 minutes'

149

>>> precisedelta(delta, minimum_unit="microseconds")

150

'2 days, 1 hour, 33 seconds and 123 milliseconds'

151

"""

152

```

153

154

## Time Units

155

156

```python { .api }

157

from enum import Enum

158

159

class Unit(Enum):

160

"""Time units for precise delta calculations."""

161

MICROSECONDS = 0

162

MILLISECONDS = 1

163

SECONDS = 2

164

MINUTES = 3

165

HOURS = 4

166

DAYS = 5

167

MONTHS = 6

168

YEARS = 7

169

```

170

171

## Usage Examples

172

173

### Basic Time Formatting

174

175

```python

176

import datetime as dt

177

import humanize

178

179

# Current time references

180

now = dt.datetime.now()

181

past = now - dt.timedelta(hours=2, minutes=30)

182

future = now + dt.timedelta(days=3)

183

184

# Natural time expressions

185

print(humanize.naturaltime(past)) # "2 hours ago"

186

print(humanize.naturaltime(future)) # "3 days from now"

187

188

# Pure duration without tense

189

print(humanize.naturaldelta(dt.timedelta(hours=2, minutes=30))) # "2 hours"

190

191

# Date formatting

192

today = dt.date.today()

193

print(humanize.naturalday(today)) # "today"

194

print(humanize.naturalday(today - dt.timedelta(days=1))) # "yesterday"

195

```

196

197

### Precise Time Calculations

198

199

```python

200

import datetime as dt

201

import humanize

202

203

# Complex time period

204

delta = dt.timedelta(days=2, hours=1, minutes=33, seconds=12, microseconds=123000)

205

206

# Default precision

207

print(humanize.precisedelta(delta))

208

# "2 days, 1 hour, 33 minutes and 12.12 seconds"

209

210

# Higher precision

211

print(humanize.precisedelta(delta, minimum_unit="microseconds"))

212

# "2 days, 1 hour, 33 minutes, 12 seconds and 123 milliseconds"

213

214

# Suppressing units

215

print(humanize.precisedelta(delta, suppress=['minutes', 'seconds']))

216

# "2 days and 1.55 hours"

217

```

218

219

### Minimum Unit Control

220

221

```python

222

import datetime as dt

223

import humanize

224

225

short_time = dt.timedelta(milliseconds=500)

226

227

print(humanize.naturaldelta(short_time, minimum_unit="milliseconds"))

228

# "500 milliseconds"

229

230

print(humanize.naturaldelta(short_time, minimum_unit="seconds"))

231

# "a moment"

232

```

233

234

## Error Handling

235

236

Time formatting functions handle edge cases gracefully:

237

238

- Invalid date/datetime objects return their string representation

239

- Non-convertible values return the original value as a string

240

- Overflow errors in date calculations are handled safely

241

- Timezone-aware datetimes are converted to naive datetimes automatically