1"""fontTools.misc.timeTools.py -- tools for working with OpenType timestamps.
2"""
3
4import os
5import time
6from datetime import datetime, timezone
7import calendar
8
9
10epoch_diff = calendar.timegm((1904, 1, 1, 0, 0, 0, 0, 0, 0))
11
12DAYNAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
13MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
14			  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
15
16
17def asctime(t=None):
18	"""
19	Convert a tuple or struct_time representing a time as returned by gmtime()
20	or localtime() to a 24-character string of the following form:
21
22	>>> asctime(time.gmtime(0))
23	'Thu Jan  1 00:00:00 1970'
24
25	If t is not provided, the current time as returned by localtime() is used.
26	Locale information is not used by asctime().
27
28	This is meant to normalise the output of the built-in time.asctime() across
29	different platforms and Python versions.
30	In Python 3.x, the day of the month is right-justified, whereas on Windows
31	Python 2.7 it is padded with zeros.
32
33	See https://github.com/fonttools/fonttools/issues/455
34	"""
35	if t is None:
36		t = time.localtime()
37	s = "%s %s %2s %s" % (
38		DAYNAMES[t.tm_wday], MONTHNAMES[t.tm_mon], t.tm_mday,
39		time.strftime("%H:%M:%S %Y", t))
40	return s
41
42
43def timestampToString(value):
44	return asctime(time.gmtime(max(0, value + epoch_diff)))
45
46def timestampFromString(value):
47	wkday, mnth = value[:7].split()
48	t = datetime.strptime(value[7:], ' %d %H:%M:%S %Y')
49	t = t.replace(month=MONTHNAMES.index(mnth), tzinfo=timezone.utc)
50	wkday_idx = DAYNAMES.index(wkday)
51	assert t.weekday() == wkday_idx, '"' + value + '" has inconsistent weekday'
52	return int(t.timestamp()) - epoch_diff
53
54def timestampNow():
55	# https://reproducible-builds.org/specs/source-date-epoch/
56	source_date_epoch = os.environ.get("SOURCE_DATE_EPOCH")
57	if source_date_epoch is not None:
58		return int(source_date_epoch) - epoch_diff
59	return int(time.time() - epoch_diff)
60
61def timestampSinceEpoch(value):
62	return int(value - epoch_diff)
63
64
65if __name__ == "__main__":
66	import sys
67	import doctest
68	sys.exit(doctest.testmod().failed)
69