官术网_书友最值得收藏!

Creating a datetime object from a string

This recipe demonstrates the conversion of well-formatted strings into datetime objects. This finds application in reading timestamps from a file. Also, this is helpful while receiving timestamps as JSON data over web APIs.

How to do it…

Execute the following steps for this recipe:

  1. Import the necessary modules from the Python standard library:
>>> from datetime import datetime
  1. Create a string representation of timestamp with date, time, and time zone. Assign it to now_str:
>>> now_str = '13-1-2021 15:53:39 +05:30'
  1. Convert now_str to now, a datetime.datetime object. Print it:
>>> now = datetime.strptime(now_str, "%d-%m-%Y %H:%M:%S %z")
>>> print(now)

We get the following output:

2021-01-13 15:53:39+05:30
  1. Confirm that now is of the datetime type:
>>> print(type(now))

We get the following output:

<class 'datetime.datetime'>

How it works...

In step 1, you import the datetime class from the datetime module. In step 2, you create a string holding a valid timestamp and assign it to a new attribute, now_str. The datetime module has a strptime() method which can convert a string holding a valid timestamp in a specific format to a datetime object. In step 3, you convert now_str, a string in the format DD-MM-YYYY HH:MM:SS +Z, to now. In step 4, you confirm that now is indeed an object of the datetime type. The directives used in step 3 are the same as those described in the Converting a datetime object to a string recipe.

There's more

When reading a string into a datetime object, the entire string should be consumed with appropriate directives. Consuming a string partially will throw an exception, as shown in the following code snippet. The error message shows what data was not converted and can be used to fix the directives provided to the strptime() method.

Try to convert now_str to a datetime object using strptime() method. Pass a string with directives for only the date part of the string. Note the error:

>>> now = datetime.strptime(now_str, "%d-%m-%Y")

The output is as follows:

# Note: It's expected to have an error below
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-96-dc92a0358ed8> in <module>
----> 1 now = datetime.strptime(now_str, "%d-%m-%Y")
2 # Note: It's expected to get an error below

/usr/lib/python3.8/_strptime.py in _strptime_datetime(cls, data_string, format)
566 """Return a class cls instance based on the input string and the
567 format string."""
--> 568 tt, fraction, gmtoff_fraction = _strptime(data_string, format)
569 tzname, gmtoff = tt[-2:]
570 args = tt[:6] + (fraction,)

/usr/lib/python3.8/_strptime.py in _strptime(data_string, format)
350 (data_string, format))
351 if len(data_string) != found.end():
--> 352 raise ValueError("unconverted data remains: %s" %
353 data_string[found.end():])
354

ValueError: unconverted data remains: 15:53:39 +05:30
主站蜘蛛池模板: 巨野县| 顺平县| 敖汉旗| 巴彦淖尔市| 集安市| 平泉县| 阿拉善右旗| 新兴县| 宝山区| 黑水县| 芦溪县| 香港 | 林口县| 通化市| 开平市| 昌图县| 德庆县| 通许县| 察哈| 延吉市| 鲁山县| 新安县| 铜陵市| 淅川县| 汝南县| 宝丰县| 开鲁县| 温宿县| 科尔| 盐边县| 铜梁县| 凯里市| 新宁县| 平塘县| 宜春市| 偏关县| 博白县| 潮州市| 呼伦贝尔市| 正定县| 五家渠市|