PLEAC = Language Examples Alike Cookbook by Guillaume Cottenceau et al. PLEAC examples were drawn from the "Perl Cookbook" by Tom Christiansen & Nathan Torkington, published by O'Reilly, and used with the publisher's permission. They provide a nice range of examples oriented toward data munging, the type of work I tend to want to do first when learning a new language.
The Julia examples below are principally translations from the Python version
I'm learning as I go, so the code below probably doesn't represent best practice. Your suggestions are welcome! Please file an issue or make a pull request to the github repo.
The examples are not complete. Missing items are generally noted in comments.
VERSION
v"0.2.0-rc4"
using Datetime
n=now()
2013-11-23T14:27:11 UTC
Julia includes a small set of c style time functions in its base modules. It addition there are the Calendar.jl and Datetime.jl packages. Many of the examples below use Datetime.jl. Examples related to epoch rely more on the Base time functions. Calendar.jl is also used in some cases; it is currently particularly strong at parsing and formatting (Calendar.jl is also good for internationalized formats, but those are not exercised in this notebook).
t=time() #current time, unix epoch
1.385216831873e9
dump(t)
Float64 1.385216831873e9
t2 = ccall(:clock_now, Float64, ()) #Seconds since unix epoch
1.385216832207e9
t-t2
-0.3340001106262207
time() is local (EDT in my case). Year field of 113 rather than 2013 reflects base of 1900.
Month field of 10 rather than 11 reflect zero-based month numbering.
tm=TmStruct(time()) #
TmStruct(12,27,9,23,10,113,6,326,0,0,0,0,0,0)
tm2 = TmStruct(23,32,10,5,10,113,2,308,0)
TmStruct(23,32,10,5,10,113,2,308,0,0,0,0,0,0)
strftime("%A",time()) #correct
"Saturday"
help(TmStruct)
Loading help data... Base.TmStruct([seconds]) Convert a number of seconds since the epoch to broken-down format, with fields "sec", "min", "hour", "mday", "month", "year", "wday", "yday", and "isdst".
dump(tm)
TmStruct sec: Int32 12 min: Int32 27 hour: Int32 9 mday: Int32 23 month: Int32 10 year: Int32 113 wday: Int32 6 yday: Int32 326 isdst: Int32 0 _10: Int32 0 _11: Int32 0 _12: Int32 0 _13: Int32 0 _14: Int32 0
tns=time_ns() #high precision time
0x0000e883391245e1
strftime(t)
"11/23/2013 9:27:11 AM"
The Window C lib doesn't appear to include strptime(), so maybe a Julia version? Python does this in /Lib/_strptime.py
methods(Base.strptime)
# 2 methods for generic function "strptime": strptime(timestr::Union(ASCIIString,UTF8String)) at libc.jl:48 strptime(fmt::Union(ASCIIString,UTF8String),timestr::Union(ASCIIString,UTF8String)) at libc.jl:50
Base.strptime("%Y/%m/%d","2013/11/4")
symbol could not be found strptime (-1): The specified procedure could not be found.
WARNING: backtraces on your platform are often misleading or partially incorrect
ccall: could not find function strptime at In[15]:1 in strptime at libc.jl:51
TmStruct(time())
TmStruct(14,27,9,23,10,113,6,326,0,0,0,0,0,0)
help(ByteString)
Union(ASCIIString,UTF8String) is of type DataType : UnionType supertype: Type{T<:Top} fields : (:types,)
isa("2013/11/4",ByteString)
true
Datetime is a package created by @karbarcca. It can be installed via the package manager. You can find source code and documentation at: https://github.com/karbarcca/Datetime.jl.
Datetime.today()
2013-11-23
Datetime.now()
2013-11-23T14:27:14 UTC
Datetime.calendar(Datetime.today())
ISOCalendar
Datetime.calendar(now())
ISOCalendar
Datetime.timezone(now())
Zone0
Datetime.offset(UTC)
0
Datetime.today() + Datetime.days(4)
2013-11-27
Datetime.today() - Datetime.weeks(1)
2013-11-16
type cannot be constructed at In[133]:1
Calendar.jl builds on ICU.jl to provide an internationalized set of dates and times. It knows how to query the computer for local timezone settings and provides parsing and formatting options not currently available with Datetime.jl. It does require ICU binaries, so set-up can be a bit harder than Datetime.jl.
using ICU
ICU.getDefaultTimeZone()
"America/New_York"
ICU.getNow() #epoch
1.385216836751e12
ICU.ICUCalendar()
ICUCalendar(Ptr{Void} @0x000000000319f1f0)
using Calendar
t0=Calendar.now()
Nov 23, 2013, 9:27:17 AM EST
t = ymd_hms(2013, 3, 10, 1, 59, 59)
Mar 10, 2013, 1:59:59 AM EST
typeof(t)
CalendarTime (constructor with 1 method)
Warning: using Calendar.now in module Main conflicts with an existing identifier.
t + days(2)
Mar 12, 2013, 2:59:59 AM EDT
delta =t0-t
258 days + 7 hours + 27 minutes + 17.86600000038743 seconds
dump(delta)
FixedCalendarDuration millis: Float64 2.2318037866e10
s = Calendar.format("yyyy-MMMM-dd EEE HH:mm:ss x", t)
"2013-March-10 Sun 01:59:59 -05"
t2 = Calendar.parse("yyyy-MMMM-dd EEE HH:mm:ss V", s)
Mar 10, 2013, 1:59:59 AM EST
timezone(t2, "UTC")
Mar 10, 2013, 6:59:59 AM GMT
d = Datetime.today()
2013-11-23
tmd = TmStruct(0,0,0,Datetime.day(d), Datetime.month(d)-1,Datetime.year(d)-1900,
Datetime.dayofweek(d), Datetime.dayofyear(d),0)
TmStruct(0,0,0,23,10,113,6,327,0,0,0,0,0,0)
#correct
strftime("Today is Day %w of the week (a %A). Day %d of the month (%B)",tmd)
"Today is Day 6 of the week (a Saturday). Day 23 of the month (November)"
strftime("Day %j of the year(%Y), in week %W of the year.",tmd)
"Day 328 of the year(2013), in week 47 of the year."
function Date2TmStruct(d::Datetime.Date)
tmd = TmStruct(0,0,0,Datetime.day(d), Datetime.month(d)-1,Datetime.year(d)-1900,
Datetime.dayofweek(d),Datetime.dayofyear(d),0)
return tmd
end
Date2TmStruct (generic function with 1 method)
tmd=Date2TmStruct(d)
TmStruct(0,0,0,23,10,113,6,327,0,0,0,0,0,0)
dd = date(tmd.year+1900,tmd.month+1,tmd.mday)
2013-11-23
function TmStruct2Date(tmd::TmStruct)
return Datetime.date(tmd.year+1900,tmd.month+1,tmd.mday)
end
TmStruct2Date (generic function with 1 method)
TmStruct2Date(tmd)
2013-11-23
import Base.strftime
function strftime(fmt::String, d::Datetime.Date)
"""strftime date formatting using Datetime.Date"""
tmd = Date2TmStruct(d)
return strftime(fmt, tmd)
end
strftime (generic function with 4 methods)
strftime("%A",Datetime.today())
"Saturday"
strftime("%Y-%m-%d", now())
"2013-11-23"
dt=now()
2013-11-25T18:32:33 UTC
#Year field of 113 rather than 2013 reflects base of 1900.
#Month field of 10 rather than 11 reflect zero-based month numbering.
tm = TmStruct(23,32,10,5,10,113,2,308,0)
dump(tm)
TmStruct sec: Int32 23 min: Int32 32 hour: Int32 10 mday: Int32 5 month: Int32 10 year: Int32 113 wday: Int32 2 yday: Int32 308 isdst: Int32 0 _10: Int32 0 _11: Int32 0 _12: Int32 0 _13: Int32 0 _14: Int32 0
Datetime.second(dt), Datetime.minute(dt), Datetime.hour(dt),
Datetime.day(dt), Datetime.month(dt), Datetime.year(dt),
Datetime.dayofweek(dt), Datetime.dayofyear(dt)
(33,32,18,25,11,2013,1,329)
? isdst should be 0 or 1. How do we get it from datetime? Maybe we can ignore it for formatting?
tmdt = TmStruct(Datetime.second(dt), Datetime.minute(dt), Datetime.hour(dt),
Datetime.day(dt), Datetime.month(dt)-1,Datetime.year(dt)-1900,
Datetime.dayofweek(dt)-1,Datetime.dayofyear(dt),0)
TmStruct(33,32,18,25,10,113,0,329,0,0,0,0,0,0)
?TmStruct
Base.TmStruct([seconds]) Convert a number of seconds since the epoch to broken-down format, with fields "sec", "min", "hour", "mday", "month", "year", "wday", "yday", and "isdst".
function TmStruct2Datetime(tmd::TmStruct)
return datetime(int64(tmd.year+1900),int64(tmd.month+1),int64(tmd.mday), int64(tmd.hour), int64(tmd.min), int64(tmd.sec) )
end
TmStruct2Datetime (generic function with 1 method)
tmd =TmStruct(time())
TmStruct(17,49,13,25,10,113,1,328,0,0,0,0,0,0)
TmStruct2Datetime(tm)
2013-11-25T13:42:53 UTC
#strftime("%Y-%m-%d %h:%M:%s",time())
strftime("%Y %H:%M:%S",time())
"2013 13:49:18"
function DateTime2TmStruct(d::Datetime.DateTime)
tmdt = TmStruct(Datetime.second(dt), Datetime.minute(dt), Datetime.hour(dt),
Datetime.day(dt), Datetime.month(dt)-1,Datetime.year(dt)-1900,
Datetime.dayofweek(dt),Datetime.dayofyear(dt),0)
return tmdt
end
DateTime2TmStruct (generic function with 1 method)
function strftime(fmt::String, dt::Datetime.DateTime)
"""strftime date formatting using Datetime.DateTime"""
tmdt = DateTime2TmStruct(dt)
return strftime(fmt, tmdt)
end
strftime (generic function with 6 methods)
strftime("%A",dt)
"Saturday"
using Datetime
dayofyear(today())
327
println("Today is day $(dayofyear(today())) of the current year.")
Today is day 327 of the current year.
println("Today is day $(dayofyear(today())) of $(year(today())).")
Today is day 327 of 2013.
println("The date is $(today()).")
The date is Nov 23, 2013, 12:00:00 AM EST.
now()
2013-11-23T14:27:26 UTC
epoch_dt = datetime(1970,1,1,0,0,0)
1970-01-01T00:00:00 UTC
now() - epoch_dt
1385216871852
function datetime2unix(dt::DateTime)
#returns difference in seconds, to match Base.time()
#unix2datetime{T<:Offsets}(x::Int64,tz::Type{T}) = convert(DateTime{CALENDAR,tz},UNIXEPOCH + x + leaps(UNIXEPOCH + x))
epoch_dt = datetime(1970,1,1,0,0,0)
diff_secs = (dt - epoch_dt - Datetime.leaps(dt))/1000
return diff_secs
end
datetime2unix (generic function with 1 method)
dt=now()
2013-11-23T14:27:27 UTC
ep=datetime2unix(dt)
1.385216847391e9
(time() - datetime2unix(now())) #seconds difference
0.0
(time() - datetime2unix(now(UTC)))
-0.003999948501586914
(time() - datetime2unix(now(EDT)))
-0.006000041961669922
println("Epoch seconds: $(time())")
Epoch seconds: 1.385216848683e9
t= time()
1.385216848954e9
#correct utc
unix2datetime( int64(t*1000) , UTC)
2013-11-23T14:27:28 UTC
#correct local
unix2datetime( int64(t*1000) , EDT)
2013-11-23T09:27:28 EST
function time2datetime(t::Float64, timezone)
"""time() style epoch to Datetime in specified timezone."""
return unix2datetime( int64(t*1000) , timezone)
end
time2datetime_utc(t::Float64) = time2datetime(t::Float64, UTC)
time2datetime_est(t::Float64) = time2datetime(t::Float64, EDT)
time2datetime_est (generic function with 1 method)
# correct
time2datetime_est(t)
2013-11-23T09:27:28 EST
mydate = date(2013,1,2)
2013-01-02
println("One day in the future is $(mydate + day(1))")
no method day(Int64,) at In[81]:1
println("Two weeks in the past is $(mydate + week(-2))")
no method week(Int64,) at In[82]:1
dt2 = date(2013,2,14)
dt2 - mydate
43
birthtime = datetime(1973,1,18,3,45,50)
1973-01-18T03:45:50 UTC
then = birthtime + seconds(5)+minutes(17)+hours(2)+days(55)
no method +(DateTime{ISOCalendar,Zone0},FixedCalendarDuration) at In[85]:1 in + at operators.jl:68
println("Then is $then")
then not defined at In[86]:1
when = date(1973,1,18) + days(55)
println("Nat was 55 days old on $when")
no method +(Date{ISOCalendar},FixedCalendarDuration) at In[87]:1
Date differences are given in days as a Day
diff = dt2 - mydate
43
dump(diff)
Day{ISOCalendar} 43 days
Datetime differences are given in milliseconds as an Int64
dt1 = now()
2013-11-23T14:27:44 UTC
dt2 = now()
2013-11-23T14:27:44 UTC
diff_dt = dt2-dt1
1
dump(diff_dt)
Int64 1
bree = datetime(1981,6,16,4,35,25)
nat = datetime(1973,1,18,3,45,50)
dseconds = (bree-nat)/1000
float_days = dseconds/(60*60*24)
ddays = int(float_days) #convert from milliseconds to days
3071
println("There were $(int(ddays)) days between Nat and Bree")
There were 3071 days between Nat and Bree
dweeks = div(ddays,7)
438
xdays = ddays % 7
5
day_fraction = float_days - ddays
0.03451388888879592
xhours = int(floor(24*day_fraction,0))
0
dminutes = int(dseconds/60)
4422290
day_seconds = dseconds-(ddays*24*60*60)
2982.0
xhours= int(div(day_seconds, 60*60))
0
xminutes = int(div(day_seconds, 60))
49
xseconds = int(day_seconds % 60)
42
#check the sum
xseconds + 60*xminutes + 60*60*xhours
2982
println("$weeks weeks, $xdays days, $xhours:$xminutes:$xseconds")
weeks weeks, 5 days, 0:49:42
bree = ymd_hms(1981,6,16,4,35,25)
nat = ymd_hms(1973,1,18,3,45,50)
Jan 18, 1973, 3:45:50 AM EST
delta=bree-nat
3070 days + 23 hours + 49 minutes + 35 seconds
delta is in milliseconds, just like Datetime.jl, so the rest is unchanged from above
dump(delta)
FixedCalendarDuration millis: Float64 2.65333775e11
using Datetime.jl
when = Datetime.date(1981,6,16)
1981-06-16
Datetime.dayofweek(when) # = Tuesday
2
Datetime.year(when), Datetime.month(when), Datetime.day(when)
(1981,6,16)
Formatted Datetime and Formatted Date
strftime("%A",Datetime.today())
"Saturday"
strftime(when)
"6/16/1981 12:00:00 AM"
#this is correct
strftime("Today is Day %w of the week (a %A). Day %d of the month (%B)",Datetime.today())
"Today is Day 6 of the week (a Saturday). Day 23 of the month (November)"
strftime("1981-06-16 was Day %w of the week (a %A). Day %d of the month (%B)",when)
"1981-06-16 was Day 2 of the week (a Tuesday). Day 16 of the month (June)"
strftime("Day %j of the year(%Y), in week %W of the year.",when)
"Day 168 of the year(1981), in week 24 of the year."
# nope
datetime("Tue Jun 16 20:18:03 1981")
no method datetime(ASCIIString,) at In[118]:2
Calendar.parse("EEE MMM DD HH:mm:ss yyyy", "Tue Jun 16 20:18:03 1981")
Jan 16, 1981, 8:18:03 PM EST
#time.strptime("16/6/1981", "%d/%m/%Y")
Calendar.parse("DD/M/yyyy","16/6/1981")
Jan 16, 1981, 12:00:00 AM EST
dt=Datetime.now()
strftime("The date is %A (%a) %d/%m/%Y",dt)
"The date is Saturday (Sat) 23/11/2013"
cdt = Calendar.now()
Calendar.format("The date is yyyy",cdt)
""
"""The date is $(Calendar.format(" EEEE (EEE) d/MM/yyyy",cdt))"""
"The date is Saturday (Sat) 23/11/2013"
Calendar.dayofweek(cdt)
7
tic()
0x0000e88a82c18c27
elapsed=toc()
elapsed time: 0.014813308 seconds
0.014813308
# from https://github.com/JuliaLang/julia/issues/4478
function f1(n)
sum = 0.0
g1(k) = 1.0/k
for i = 1:n
sum += g1(i)
end
sum
end
f1 (generic function with 1 method)
f1(99)
5.177377517639621
@time f1(1e6)
elapsed time: 0.128212042 seconds (48085868 bytes allocated)
14.392726722864989
sleep(3.1) #sleep for 4 seconds
@time( sleep(3.1) )
elapsed time: 3.10030402 seconds (408 bytes allocated)
will not solve
;ipython nbconvert 3_pleac_datetime.ipynb
[NbConvertApp] Using existing profile dir: u'C:\\Users\\keithc\\.ipython\\profile_default' [NbConvertApp] Converting notebook 3_pleac_datetime.ipynb to html [NbConvertApp] Support files will be in 3_pleac_datetime_files\ [NbConvertApp] Loaded template html_full.tpl [NbConvertApp] Writing 314208 bytes to 3_pleac_datetime.html