Ben Chuanlong Du's Blog

It is never too late to learn.

Hands on the datetime Module in Python

Comment

A Datetime object cannot be compared with a string directly. However, pandas Series of datetime objects can be compared with string date directly (both by operators and methods). The comparison is done by parsing the string to a datetime object. An exception will be thrown if the string cannot be parsed into a datetime object.

In [1]:
import datetime

Construct a date/datetime Object from String

In [2]:
datetime.datetime.strptime("2017-01-09", "%Y-%m-%d")
Out[2]:
datetime.datetime(2017, 1, 9, 0, 0)

Time in micro seconds resolution.

In [6]:
datetime.datetime.strptime("2017-01-18 09:21:29.000000", "%Y-%m-%d %H:%M:%S.%f")
Out[6]:
datetime.datetime(2017, 1, 18, 9, 21, 29)

Use suffixing zeros if nano seconds is provided.

In [3]:
datetime.datetime.strptime("2017-01-18 09:21:29.000000000", "%Y-%m-%d %H:%M:%S.%f000")
Out[3]:
datetime.datetime(2017, 1, 18, 9, 21, 29)

Construct a date/datetime Object by Specifying Year, Month, Day, etc.

In [8]:
datetime.date(2017, 1, 9)
Out[8]:
datetime.date(2017, 1, 9)

Construct a date/datetime Object from Timestamp

In [ ]:
datetime.fromtimestamp(t3)

now/today

Get the current system time.

In [36]:
datetime.now()
Out[36]:
datetime.datetime(2018, 5, 6, 4, 24, 0, 949796)
In [8]:
str(datetime.now())
Out[8]:
'2018-05-06 10:11:57.277133'
In [35]:
datetime.today()
Out[35]:
datetime.datetime(2018, 5, 6, 4, 23, 58, 870716)

Get timezone name. By default, datetime is not aware of timezone.

Get the current UTC time.

utcnow

In [2]:
datetime.utcnow()
Out[2]:
datetime.datetime(2018, 5, 6, 4, 9, 42, 210413)
In [28]:
datetime.utcnow().date()
Out[28]:
datetime.date(2018, 5, 6)

It seems that now and today are equivalent.

date

In [37]:
datetime.now().date()
Out[37]:
datetime.date(2018, 5, 6)

Timzezone

By default, datetime is not aware of timezone which is fucking stupid! For this reason, the utcnow does return UTC time at all!

In [38]:
datetime.today().tzname()
In [39]:
datetime.now().tzname()

now and utcnow are the same, which is fucking stpid and error-prone!

In [40]:
print(datetime.now())
print(datetime.utcnow())
2018-05-06 04:25:45.744147
2018-05-06 04:25:45.744282

Timestamp

In [3]:
datetime.now().timestamp()
Out[3]:
1525600136.106702
In [4]:
datetime.utcnow().timestamp()
Out[4]:
1525600384.425062
In [7]:
datetime.fromtimestamp(datetime.now().timestamp())
Out[7]:
datetime.datetime(2018, 5, 6, 10, 11, 1, 920892)

Month Day

In [10]:
date.today().day
Out[10]:
11

Weekday

Monday is 0 and Sunday is 6.

In [17]:
today = date.today()
today
Out[17]:
datetime.date(2017, 10, 11)
In [16]:
date.today().weekday() - 5 + 7
Out[16]:
4
In [18]:
today - 4
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-ac1ac82a5046> in <module>()
----> 1 today - 4

TypeError: unsupported operand type(s) for -: 'datetime.date' and 'int'

TimeDelta

Arithmatical operation is supported via the TimeDelta class.

https://stackoverflow.com/questions/441147/how-can-i-subtract-a-day-from-a-python-date

In [1]:
from datetime import date, timedelta

d = date.today() - timedelta(days=1)
d
Out[1]:
datetime.date(2018, 6, 28)
In [3]:
timedelta(days=1).days
Out[3]:
1

Convert a datetime Object to String

By default, a datetime object is convertd to a string using the format %Y-%m-%d %H:%M:%S.%f. Please refer to Format Date and Time in Python for more details on how format a datetime object.

In [3]:
now = datetime.datetime.now()
now
Out[3]:
datetime.datetime(2020, 3, 11, 11, 53, 42, 533996)
In [4]:
str(now)
Out[4]:
'2020-03-11 11:53:42.533996'
In [5]:
f"The time now is {now}"
Out[5]:
'The time now is 2020-03-11 11:53:42.533996'
In [ ]:
 

Comments