Python
The datetime module from the Python standard library allows for the implementation of
the most important date and time-related tasks.
[ 85 ]
We start by importing the module:
In [ 1 ]: import datetime as dt
Two different functions provide the exact current date and time:
In [ 2 ]: dt.datetime.now()
Out[2]: datetime.datetime(2014, 9, 14, 19, 22, 24, 366619)
In [ 3 ]: to = dt.datetime.today()
to
Out[3]: datetime.datetime(2014, 9, 14, 19, 22, 24, 491234)
The resulting object is a datetime object:
In [ 4 ]: type(to)
Out[4]: datetime.datetime
The method weekday provides the number for the day of the week, given a datetime
object:
In [ 5 ]: dt.datetime.today().weekday()
# zero-based numbering; 0 = Monday
Out[5]: 6
Such an object can, of course, be directly constructed:
In [ 6 ]: d = dt.datetime( 2016 , 10 , 31 , 10 , 5 , 30 , 500000 )
d
Out[6]: datetime.datetime(2016, 10, 31, 10, 5, 30, 500000)
In [ 7 ]: print d
Out[7]: 2016-10-31 10:05:30.500000
In [ 8 ]: str(d)
Out[8]: ‘2016-10-31 10:05:30.500000’
From such an object you can easily extract, for example, year, month, day information,
and so forth:
In [ 9 ]: d.year
Out[9]: 2016
In [ 10 ]: d.month
Out[10]: 10
In [ 11 ]: d.day
Out[11]: 31
In [ 12 ]: d.hour
Out[12]: 10
Via the method toordinal, you can translate the date information to ordinal number
representation:
In [ 13 ]: o = d.toordinal()
o
Out[13]: 736268
This also works the other way around. However, you lose the time information during this
process:
In [ 14 ]: dt.datetime.fromordinal(o)
Out[14]: datetime.datetime(2016, 10, 31, 0, 0)
On the other hand, you can separate out the time information from the datetime object,