-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy pathutils.py
More file actions
58 lines (47 loc) · 1.78 KB
/
utils.py
File metadata and controls
58 lines (47 loc) · 1.78 KB
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
"""Utility functions for import services."""
import re
from datetime import datetime
from typing import Any
def clean_filename(name: str) -> str: # pragma: no cover
"""Clean a string to be used as a filename.
Args:
name: The string to clean.
Returns:
A cleaned string suitable for use as a filename.
"""
# Replace common punctuation and whitespace with underscores
name = re.sub(r"[\s\-,.:/\\\[\]\(\)]+", "_", name)
# Remove any non-alphanumeric or underscore characters
name = re.sub(r"[^\w]+", "", name)
# Ensure the name isn't too long
if len(name) > 100: # pragma: no cover
name = name[:100]
# Ensure the name isn't empty
if not name: # pragma: no cover
name = "untitled"
return name
def format_timestamp(timestamp: Any) -> str: # pragma: no cover
"""Format a timestamp for use in a filename or title.
Args:
timestamp: A timestamp in various formats.
Returns:
A formatted string representation of the timestamp.
"""
if isinstance(timestamp, str):
try:
# Try ISO format
timestamp = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
except ValueError:
try:
# Try unix timestamp as string
timestamp = datetime.fromtimestamp(float(timestamp)).astimezone()
except ValueError:
# Return as is if we can't parse it
return timestamp
elif isinstance(timestamp, (int, float)):
# Unix timestamp
timestamp = datetime.fromtimestamp(timestamp).astimezone()
if isinstance(timestamp, datetime):
return timestamp.strftime("%Y-%m-%d %H:%M:%S")
# Return as is if we can't format it
return str(timestamp) # pragma: no cover