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.
import datetime
Construct a date/datetime Object from String¶
datetime.datetime.strptime("2017-01-09", "%Y-%m-%d")
Time in micro seconds resolution.
datetime.datetime.strptime("2017-01-18 09:21:29.000000", "%Y-%m-%d %H:%M:%S.%f")
Use suffixing zeros if nano seconds is provided.
datetime.datetime.strptime("2017-01-18 09:21:29.000000000", "%Y-%m-%d %H:%M:%S.%f000")
Construct a date/datetime Object by Specifying Year, Month, Day, etc.¶
datetime.date(2017, 1, 9)
Construct a date/datetime Object from Timestamp¶
datetime.fromtimestamp(t3)
now/today¶
Get the current system time.
datetime.now()
str(datetime.now())
datetime.today()
Get timezone name. By default, datetime is not aware of timezone.
Get the current UTC time.
utcnow¶
datetime.utcnow()
datetime.utcnow().date()
It seems that now
and today
are equivalent.
date¶
datetime.now().date()
Timzezone¶
By default, datetime is not aware of timezone which is fucking stupid!
For this reason,
the utcnow
does return UTC time at all!
datetime.today().tzname()
datetime.now().tzname()
now
and utcnow
are the same,
which is fucking stpid and error-prone!
print(datetime.now())
print(datetime.utcnow())
Timestamp¶
datetime.now().timestamp()
datetime.utcnow().timestamp()
datetime.fromtimestamp(datetime.now().timestamp())
Month Day¶
date.today().day
Weekday¶
Monday is 0 and Sunday is 6.
today = date.today()
today
date.today().weekday() - 5 + 7
today - 4
TimeDelta¶
Arithmatical operation is supported via the TimeDelta class.
https://stackoverflow.com/questions/441147/how-can-i-subtract-a-day-from-a-python-date
from datetime import date, timedelta
d = date.today() - timedelta(days=1)
d
timedelta(days=1).days
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.
now = datetime.datetime.now()
now
str(now)
f"The time now is {now}"