Reputation: 1030
In other words, I'm looking for the equivalent of Python's datetime.utcnow().
I'm also fine with a n-tuple containing years, months and so on, up until milliseconds (or microseconds).
I had thought of using show
and then parsing the String
value, but I believe there's something more convenient.
Upvotes: 4
Views: 3538
Reputation: 120711
Re-parsing a string is very un-Haskellish, you certainly don't want that.
I'd use, from Data.Time.LocalTime
,
todSec . localTimeOfDay . utcToLocalTime utc :: UTCTime -> Data.Fixed.Pico
that gives you seconds in picosecond-resolution.
Upvotes: 4
Reputation: 17786
Seconds and milliseconds since when? Presumably there is an epoch (time zero) hiding somewhere here. You subtract the epoch from the UTCTime to get a NominalDiffTime, and then extract the seconds and milliseconds from that.
secondsSince :: UTCTime -> UTCTime -> (Integer, Int)
secondsSince t0 t1 = (i, round $ d * 1000)
where (i, d) = properFraction $ diffUTCTime t1 t0
Of course you probably want t0 to be 1/1/1970 (the Unix epoch), in which case you import Data.Time.Clock.POSIX and use utcTimeToPOSIXSeconds, which returns a NominalDiffTime.
NominalDiffTime is an instance of (amongst other things) Fractional and Num, so you have access to all the usual numeric operators when manipulating them. From an arithmetical point of view (including conversions) it is treated as a number of seconds.
When using this, do bear in mind that Unix gets time fundamentally wrong because it doesn't have any room for leap seconds. Every few years there is a day with 86401 seconds instead of the usual 86400. Back in the 70s the idea of a computer needing to know about this would have seemed absurd (clocks were generally set by the sysadmin consulting his mechanical watch), so the Unix time_t simply counts seconds since the epoch and assumes that every day has exactly 86400 seconds. NominalDiffTime is "nominal" because it makes the same assumption.
The Right Thing would have been to make time_t a struct with a day number and seconds since midnight as separate fields, and have the time arithmetic functions consult a table of leap seconds. However that would have its own set of disadvantages because new leap seconds get designated every so often, so a program could give different results when run at different times. Or to put it in Haskell terms, "diffUTCTime" would have to return a result in the IO monad.
Upvotes: 3