Dates
import datetime
x = datetime.datetime.now()
print(x)
x = datetime.datetime.now()
print(x)
# results in:
2020-06-11 12:11:37.306782
Using dir() on nested members of an import module shows all "components" including things like __init__().
import datetime
w = dir(datetime)
print(w)
#results in:
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_divide_and_round', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']
import datetime
x = datetime.datetime(2020, 4, 13)
y = dir(x)
print(y)
#results in:
['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']
There is a datetime constructor as a component of the datetime module. The fact that the module and the constructor have the same name may be a bit confusing since you have to repeat that phrase (datetime.datetime) in order to run the constructor. If you want to avoid the awkward looking repeated phrase sequence, just import only the components that you need like this:
from datetime import datetime
x = datetime.now()
print(x)
# results in:
2020-06-11 16:17:55.482387
The default format for the creation of a datetime object is (year, month, day).
strftime() formats the resulting object string using a single format parameter, denoted by a single upper or lower case letter after a % sign.
Specifying an unlisted code generates no errors but will give either unknown results or the invalid flag repeated back to the screen.
import datetime
x = datetime.datetime(2017, 9, 21)
print(x.strftime("%v"))
#results in:
%v
See all of the strftime format codes.
No comments:
Post a Comment