Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print time as #inst

Tags:

clojure

It's easy to read a date literal:

(read-string "#inst \"2012\"")
        ;;; ⇒ #inst "2012-01-01T00:00:00.000-00:00"

How can I output a date as a #inst... literal?

This does not work:

(pr-str (clj-time.core/now))
        ;;; ⇒ "#<DateTime 2013-07-09T17:26:30.058Z>"

(read-string (pr-str (clj-time.core/now)))
        ;;; ⇒ <err>
        ;;;   RuntimeException Unreadable form  clojure.lang.Util.runtimeException (Util.java:219)
like image 407
event_jr Avatar asked Jul 09 '13 17:07

event_jr


People also ask

How do you print date and time?

Click the Print Settings tab. Under Headers and Footers, click Header or Footer. In the Insert AutoText box, click Field. In the Select a Field or Group dialog box, select the field containing the date or time you want to appear in the header or footer.

How do I print the current time in Python?

Python datetime:now(tz=None) returns the current local date and time. If optional argument tz is None or not specified, this is like today(). date. strftime(format) returns a string representing the date, controlled by an explicit format string.

How do I print UTC time in Python?

datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC. Lastly, use the timestamp() to convert the datetime object, in UTC, to get the UTC timestamp.


1 Answers

When you read in an #inst literal, by default, a java.util.Date instance is created. These have a method defined for print-method (a multimethod responsible for printed representations of objects) in the clojure.instant namespace (the relevant fragment of the 1.5.1 source is here).

clj-time uses the DateTime type from Joda-Time, which has no custom print-method method set up. This makes sense, since having a print-method which produces a representation which doesn't round-trip is rarely desirable. In order for it to round-trip, you'd have to use a non-standard #inst reader. To achieve that, if you're reading edn data, you can use clojure.edn/read (or read-string) passing the appropriate reader in as documented in its docstring:

(require '[clojure.edn :as edn])

(edn/read {:readers {'inst your-inst-reader}} rdr)

When using clj-time, your-inst-reader will be something like #(clj-time.format/parse some-formatter %). You can then provide a matching print-method definition following the example of clojure.instant. (Or you could just provide the print-method definition and remember that you won't get perfect roundtripping; clj-time provides very convenient coercion functions -- see below -- so this might be ok.)

Alternatively you could print and read java.util.Date instances and convert them to and from DateTimes; there are functions for doing that in clj-time.coerce.

like image 99
Michał Marczyk Avatar answered Oct 21 '22 19:10

Michał Marczyk