Return a timestamp representing the datetime object (assumed to be in UTC time) or the current UTC time (if dt == None) formatted using the ISO 8601 standard as a basis, extended to be path safe is path_safe is True. The Python isoformat returns a time stamp that complies with this
(dt=None, path_safe=True)
| 33 | |
| 34 | |
| 35 | def time2tstamp(dt=None, path_safe=True): |
| 36 | """ |
| 37 | Return a timestamp representing the datetime object (assumed to be in UTC |
| 38 | time) or the current UTC time (if dt == None) formatted using the ISO 8601 |
| 39 | standard as a basis, extended to be path safe is path_safe is True. |
| 40 | |
| 41 | The Python isoformat returns a time stamp that complies with this standard |
| 42 | but has limitations when used in a file or directory name. Here we |
| 43 | transform the returned time stamp such that the result still complies with |
| 44 | the ISO standard and can be safely used as part of a of file or directory |
| 45 | name in a portable and OS safe fashion including on Windows where colons |
| 46 | are not allowed in file names, or on posix where / denotes a path segment |
| 47 | separator. |
| 48 | |
| 49 | For times, the ISO 8601 format specifies either a colon : (extended format) |
| 50 | or nothing as a separator (basic format). Here Python defaults to using a |
| 51 | colon. We therefore remove all the colons to be safe across filesystems. (a |
| 52 | colon is not a valid path char on Windows) |
| 53 | |
| 54 | Another character may show up in the ISO representation such as / for time |
| 55 | intervals. We could replace the forward slash with a double hyphen (--) as |
| 56 | a separator instead (see Section 4.4.2 of the ISO standard). However since |
| 57 | there are several places where hyphens are used, this makes it difficult to |
| 58 | parse back. Instead we use an _ (underscore) to make the time stamp easier |
| 59 | to convert back to a datetime object. |
| 60 | """ |
| 61 | # TODO: check that the dt is effectively in UTC |
| 62 | datim = dt or datetime.utcnow() |
| 63 | iso = datim.isoformat() |
| 64 | if path_safe: |
| 65 | iso = iso.replace(":", "").replace("/", "_") |
| 66 | return iso |
| 67 | |
| 68 | |
| 69 | def tstamp2time(stamp): |