which then gives you a time object:
In [ 15 ]: t = dt.datetime.time(d)
t
Out[15]: datetime.time(10, 5, 30, 500000)
In [ 16 ]: type(t)
Out[16]: datetime.time
Similarly, you can separate out the date information only, ending up with a date object:
In [ 17 ]: dd = dt.datetime.date(d)
dd
Out[17]: datetime.date(2016, 10, 31)
Often, a certain degree of precision is sufficient. To this end, you can simply replace
certain attributes of the datetime object with literal:
In [ 18 ]: d.replace(second= 0 , microsecond= 0 )
Out[18]: datetime.datetime(2016, 10, 31, 10, 5)
timedelta is another class of objects that result from arithmetic operations on the other
date-time-related objects:
In [ 19 ]: td = d - dt.datetime.now()
td
Out[19]: datetime.timedelta(777, 52983, 863732)
In [ 20 ]: type(td)
Out[20]: datetime.timedelta
Again, you can access the attributes directly to extract detailed information:
In [ 21 ]: td.days
Out[21]: 777
In [ 22 ]: td.seconds
Out[22]: 52983
In [ 23 ]: td.microseconds
Out[23]: 863732
In [ 24 ]: td.total_seconds()
Out[24]: 67185783.863732
There are multiple ways to transform a datetime object into different representations, as
well as to generate datetime objects out of, say, a string object. Details are found in the
documentation of the datetime module. Here are a few examples:
In [ 25 ]: d.isoformat()
Out[25]: ‘2016-10-31T10:05:30.500000’
In [ 26 ]: d.strftime(“%A, %d. %B %Y %I:%M%p”)
Out[26]: ‘Monday, 31. October 2016 10:05AM’
In [ 27 ]: dt.datetime.strptime(‘2017-03-31’, ‘%Y-%m-%d’)
# year first and four-digit year
Out[27]: datetime.datetime(2017, 3, 31, 0, 0)
In [ 28 ]: dt.datetime.strptime(‘30-4-16’, ‘%d-%m-%y’)
# day first and two-digit year
Out[28]: datetime.datetime(2016, 4, 30, 0, 0)
In [ 29 ]: ds = str(d)
ds
Out[29]: ‘2016-10-31 10:05:30.500000’
In [ 30 ]: dt.datetime.strptime(ds, ‘%Y-%m-%d %H:%M:%S.%f’)
Out[30]: datetime.datetime(2016, 10, 31, 10, 5, 30, 500000)
In addition to the now and today functions, there is also the utcnow function, which gives
the exact date and time information in UTC (Coordinated Universal Time, formerly