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

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
主站蜘蛛池模板: 荥经县| 沙河市| 林西县| 道孚县| 荣昌县| 祁门县| 赤峰市| 平果县| 屯门区| 讷河市| 泸州市| 通辽市| 吉隆县| 连山| 启东市| 湘潭市| 亚东县| 唐海县| 黑龙江省| 邻水| 同心县| 瑞安市| 玉溪市| 阿坝县| 曲松县| 柞水县| 禄丰县| 荥经县| 江永县| 黔南| 衢州市| 宣化县| 六枝特区| 普定县| 宁国市| 乌海市| 南华县| 湖州市| 渭南市| 蒙阴县| 龙泉市|