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