Skip to content

Commit 7aad923

Browse files
author
Michael Hoenig
committed
added datetime_from_dir() for BackInTime dirs (and UTC conversion)
1 parent 4f1d7ce commit 7aad923

1 file changed

Lines changed: 33 additions & 1 deletion

File tree

src/borg_import/helpers/timestamps.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from datetime import datetime
1+
from datetime import datetime, timedelta
2+
import time
23

34

45
def datetime_from_mtime(path):
@@ -40,6 +41,37 @@ def datetime_from_string(s):
4041
raise ValueError('could not parse %r' % s)
4142

4243

44+
def datetime_from_dir(d, p=4):
45+
"""
46+
parse datetime from part of a directory name
47+
48+
returns a datetime object if the format could be parsed.
49+
raises ValueError if not.
50+
"""
51+
if type(d).__name__ == 'PosixPath':
52+
s = d.name
53+
elif type(d) == str:
54+
# in case input is just a string (for testing)
55+
s = d
56+
# get rid of trailing -??? numbers that BackInTime adds
57+
s = s[:-p].strip()
58+
for ts_format in [
59+
# Back In Time format
60+
'%Y%m%d-%H%M%S',
61+
]:
62+
try:
63+
dt = datetime.strptime(s, ts_format)
64+
# adjust time zone offset to get UTC
65+
tz = int(time.strftime('%z')[:-2])
66+
ut = dt - timedelta(hours=tz)
67+
return ut
68+
except ValueError:
69+
# didn't work with this format, try next
70+
pass
71+
else:
72+
raise ValueError('could not parse %r' % s)
73+
74+
4375
def datetime_from_file(path):
4476
"""
4577
discover backup timestamp from contents of a file.

0 commit comments

Comments
 (0)