or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-timeago

A very simple python library, used to format datetime with relative time statements like '3 hours ago'.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/timeago@1.0.x

To install, run

npx @tessl/cli install tessl/pypi-timeago@1.0.0

0

# Timeago

1

2

A very simple Python library for formatting datetime objects into human-readable relative time expressions like "3 hours ago" or "in 2 minutes". Supports 44+ languages and locales with flexible input handling for various datetime formats.

3

4

## Package Information

5

6

- **Package Name**: timeago

7

- **Language**: Python

8

- **Installation**: `pip install timeago`

9

- **Python Compatibility**: 2.5-3.5+

10

- **Dependencies**: None

11

12

## Core Imports

13

14

```python

15

import timeago

16

```

17

18

Common usage pattern:

19

20

```python

21

from timeago import format

22

```

23

24

For parser functions:

25

26

```python

27

import timeago.parser

28

# or

29

from timeago import parser

30

```

31

32

For exceptions:

33

34

```python

35

from timeago.excepts import ParameterUnvalid

36

```

37

38

## Basic Usage

39

40

```python

41

import timeago

42

from datetime import datetime, timedelta

43

44

# Basic usage with current time

45

date = datetime.now() - timedelta(hours=2)

46

print(timeago.format(date)) # "2 hours ago"

47

48

# Specify reference time and locale

49

now = datetime.now()

50

past_time = now - timedelta(minutes=30)

51

print(timeago.format(past_time, now, 'es')) # "hace 30 minutos"

52

53

# Future time expressions

54

future_time = now + timedelta(days=3)

55

print(timeago.format(future_time, now, 'en')) # "in 3 days"

56

57

# Using timedelta directly

58

delta = timedelta(minutes=15)

59

print(timeago.format(delta)) # "15 minutes ago"

60

61

# String input parsing

62

print(timeago.format("2016-05-27 21:22:02")) # relative to current time

63

```

64

65

## Capabilities

66

67

### Time Formatting

68

69

Format datetime objects into relative time expressions supporting both past ("ago") and future ("in") time periods.

70

71

```python { .api }

72

def format(date, now=None, locale='en'):

73

"""

74

Format datetime into relative time expression.

75

76

Parameters:

77

- date: datetime/timedelta/date/time/timestamp/str - Target time to format

78

- now: datetime/str/None - Reference time (defaults to current time)

79

- locale: str - Language locale code (defaults to 'en')

80

81

Returns:

82

str - Formatted relative time string

83

84

Raises:

85

timeago.excepts.ParameterUnvalid - For invalid input parameters

86

"""

87

```

88

89

### Input Parsing

90

91

Parse various input types into datetime objects for flexible input handling. These functions are available in the `timeago.parser` module.

92

93

```python { .api }

94

# Available as: timeago.parser.parse()

95

def parse(input):

96

"""

97

Parse various input types to datetime objects.

98

99

Parameters:

100

- input: datetime/date/time/int/float/str - Input to parse

101

102

Returns:

103

datetime - Parsed datetime object or None if parsing fails

104

"""

105

```

106

107

```python { .api }

108

# Available as: timeago.parser.date_to_datetime()

109

def date_to_datetime(d):

110

"""

111

Convert date object to datetime (time set to 00:00:00).

112

113

Parameters:

114

- d: date - Date object to convert

115

116

Returns:

117

datetime - Datetime object

118

"""

119

```

120

121

```python { .api }

122

# Available as: timeago.parser.time_to_datetime()

123

def time_to_datetime(t):

124

"""

125

Convert time object to datetime (using today's date).

126

127

Parameters:

128

- t: time - Time object to convert

129

130

Returns:

131

datetime - Datetime object

132

"""

133

```

134

135

```python { .api }

136

# Available as: timeago.parser.timestamp_to_datetime()

137

def timestamp_to_datetime(ts):

138

"""

139

Convert Unix timestamp to datetime object.

140

141

Parameters:

142

- ts: int/float - Unix timestamp

143

144

Returns:

145

datetime - Datetime object

146

"""

147

```

148

149

```python { .api }

150

# Available as: timeago.parser.string_to_data_time()

151

def string_to_data_time(d):

152

"""

153

Parse datetime strings in various formats.

154

155

Supported formats:

156

- "2016-05-27 21:22:02" (standard format)

157

- "2016-5-27 21:22:2" (flexible digits)

158

- "2016/05/27 21:22:02" (slash separators)

159

- "2016-05-27" (date only)

160

- "21:22:02" (time only)

161

162

Parameters:

163

- d: str - Datetime string to parse

164

165

Returns:

166

datetime - Parsed datetime object or None if parsing fails

167

"""

168

```

169

170

### Error Handling

171

172

Exception class for invalid parameters passed to timeago functions.

173

174

```python { .api }

175

class ParameterUnvalid(Exception):

176

"""

177

Exception raised for invalid parameters.

178

179

Attributes:

180

- value: str - Error message describing the invalid parameter

181

"""

182

183

def __init__(self, value):

184

"""Initialize with error message."""

185

186

def __str__(self):

187

"""Return string representation of the error."""

188

```

189

190

### Utility Functions

191

192

Internal utility functions accessible from the main module.

193

194

```python { .api }

195

# Available as: timeago.total_seconds()

196

def total_seconds(dt):

197

"""

198

Calculate total seconds from a timedelta (Python 2.6 compatibility).

199

200

Parameters:

201

- dt: timedelta - Timedelta object to convert

202

203

Returns:

204

float - Total seconds as a float

205

"""

206

```

207

208

### Locale Support

209

210

Access and configuration for internationalization support across 44+ languages.

211

212

```python { .api }

213

# Available as: timeago.locales.timeago_template()

214

def timeago_template(locale, index, ago_in):

215

"""

216

Get localized time expression template.

217

218

Parameters:

219

- locale: str - Language locale code

220

- index: int - Time unit index (0-13: just now, seconds, minutes, hours, days, weeks, months, years)

221

- ago_in: int - Time direction (0=past/ago, 1=future/in)

222

223

Returns:

224

str - Localized time expression template or callable function

225

"""

226

```

227

228

```python { .api }

229

# Available as: timeago.locales.locale_module()

230

def locale_module(mod, locale):

231

"""

232

Extract locale configuration from a locale module.

233

234

Parameters:

235

- mod: module - The timeago module reference

236

- locale: str - Language locale code

237

238

Returns:

239

list/function - Locale configuration (list of templates or function)

240

241

Raises:

242

AttributeError - If locale module cannot be loaded

243

"""

244

```

245

246

## Types

247

248

```python { .api }

249

# Built-in Python types used

250

datetime # from datetime module

251

date # from datetime module

252

time # from datetime module

253

timedelta # from datetime module

254

str # built-in string type

255

int # built-in integer type

256

float # built-in float type

257

```

258

259

## Constants

260

261

```python { .api }

262

# Module metadata

263

__version__ = '1.0.16' # Package version

264

__license__ = 'MIT' # Package license

265

266

# Default settings

267

DEFAULT_LOCALE = 'en' # Default language locale

268

269

# Internal calculation constants

270

SEC_ARRAY = [60.0, 60.0, 24.0, 7.0, 365.0 / 7.0 / 12.0, 12.0] # Time unit conversion factors

271

SEC_ARRAY_LEN = 6 # Length of SEC_ARRAY

272

```

273

274

## Supported Locales

275

276

The package supports 44+ locales with both past ("ago") and future ("in") expressions:

277

278

**European Languages**: `en`, `en_short`, `de`, `fr`, `es`, `it`, `nl`, `da`, `fi`, `sv_SE`, `nb_NO`, `nn_NO`, `pl`, `pt_BR`, `pt_PT`, `ro`, `bg`, `el`, `hu`, `sk`, `tr`, `ru`, `uk`, `lt`, `is`, `ca`, `eu`, `gl`

279

280

**Asian Languages**: `zh_CN`, `zh_TW`, `ja`, `ko`, `th`, `vi`, `my`, `ta`, `ml`

281

282

**Middle Eastern Languages**: `ar`, `fa_IR`, `he`

283

284

**South Asian Languages**: `in_BG`, `in_HI`, `in_ID`, `guj_IN`

285

286

## Examples

287

288

### Multiple Input Types

289

290

```python

291

import timeago

292

import timeago.parser

293

from datetime import datetime, date, time, timedelta

294

295

# Datetime object

296

dt = datetime(2016, 5, 27, 21, 22, 2)

297

print(timeago.format(dt))

298

299

# Date object (time defaults to 00:00:00)

300

today = date.today()

301

print(timeago.format(today))

302

303

# Time object (date defaults to today)

304

current_time = time(15, 30, 45)

305

print(timeago.format(current_time))

306

307

# Timedelta object

308

delta = timedelta(hours=1, minutes=30)

309

print(timeago.format(delta))

310

311

# Unix timestamp

312

timestamp = 1464376922.0

313

print(timeago.format(timestamp))

314

315

# String formats

316

print(timeago.format("2016-05-27 21:22:02"))

317

print(timeago.format("2016/5/27 21:22:2"))

318

print(timeago.format("2016-05-27"))

319

print(timeago.format("21:22:02"))

320

321

# Using parser functions directly

322

parsed_dt = timeago.parser.parse("2016-05-27 21:22:02")

323

print(timeago.format(parsed_dt))

324

325

# Convert date to datetime explicitly

326

date_obj = date(2016, 5, 27)

327

dt_from_date = timeago.parser.date_to_datetime(date_obj)

328

print(timeago.format(dt_from_date))

329

```

330

331

### Locale Examples

332

333

```python

334

import timeago

335

from datetime import datetime, timedelta

336

337

date = datetime.now() - timedelta(hours=2)

338

339

# English (default)

340

print(timeago.format(date, locale='en')) # "2 hours ago"

341

342

# Spanish

343

print(timeago.format(date, locale='es')) # "hace 2 horas"

344

345

# French

346

print(timeago.format(date, locale='fr')) # "il y a 2 heures"

347

348

# German

349

print(timeago.format(date, locale='de')) # "vor 2 Stunden"

350

351

# Chinese (Simplified)

352

print(timeago.format(date, locale='zh_CN')) # "2小时前"

353

354

# Japanese

355

print(timeago.format(date, locale='ja')) # "2時間前"

356

357

# Arabic

358

print(timeago.format(date, locale='ar')) # "منذ ساعتين"

359

```

360

361

### Error Handling

362

363

```python

364

import timeago

365

from timeago.excepts import ParameterUnvalid

366

367

try:

368

# Invalid date string

369

result = timeago.format("invalid-date-string")

370

except ParameterUnvalid as e:

371

print(f"Error: {e}")

372

373

try:

374

# Malformed date string

375

result = timeago.format("2016-05-27 12:23:23") # double space

376

except ParameterUnvalid as e:

377

print(f"Error: {e}")

378

```