Using Python datetime

Here is the simplest possible example of Python datetime usage:

from datetime import datetime

dt = datetime.now()

print(dt)

It will output something like:

2019-12-17 11:16:23.609382

Common incorrect usage

There is one common mistake that is done with datetime. Here is an example of such error code:

import datetime

dt = datetime.now()

print(dt)

If you run this code it will give an error:

AttributeError: module 'datetime' has no attribute 'now'

There are two way you can fix this error. The most usual way to fix it is to write "from datetime import datetime" instead of "import datetime", here is the fixed example:

from datetime import datetime

dt = datetime.now()

print(dt)

Or you can use "import datetime", but then you need to change the assignment statement:

import datetime

dt = datetime.datetime.now()

print(dt)

This is because there are several things in Python datetime module:

The module "datetime" is called after the most common class it this module, and that class is also called "datetime".

timestamp() method

To get number of seconds from "1970-01-01T00:00:00Z" you need to use datetime timestamp() method. Here is an example:

from datetime import datetime

dt = datetime.now()

print(type(dt.timestamp()))
print(dt.timestamp())
print(dt)

This code will output something like:

<class 'float'>
1576582006.392294
2019-12-17 11:26:46.392294

Create datetime object from string

Here is an example how to create datetime object from string:

from datetime import datetime

str = '2019-10-12T11:12:34.000Z'

dt = datetime.strptime(str, '%Y-%m-%dT%H:%M:%S.%fZ')
print(type(dt))
print(dt)

The output of this code:

<class 'datetime.datetime'>
2019-10-12 11:12:34

Create string from datetime object

And this is a code sample that shows how to convert datetime object to string:

from datetime import datetime

dt = datetime.now()

print(dt.strftime("%Y-%m-%d"))

It will output date like:

2019-12-17

Ivan Bessarabov
ivan@bessarabov.ru

17 december 2019