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

Converting a datetime object to a string

This recipe demonstrates the conversion of the datetime objects into strings which finds application in printing and logging. Also, this is helpful while sending 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. Fetch the current timestamp along with time zone information. Assign it to now and print it:
>>> now = datetime.now().astimezone()
  1. Cast now to a string and print it::
>>> print(str(now))

We get the following output. Your output may differ:

2020-08-12 20:55:48.366130+05:30
  1. Convert now to a string with a specific date-time format using strftime() and print it:
>>> print(now.strftime("%d-%m-%Y %H:%M:%S %Z"))

We get the following output. Your output may differ:

12-08-2020 20:55:48 +0530

How it works...

In step 1, you import the datetime class from the datetime module. In step 2, you fetch the current timestamp with time zone and assign it to a new attribute, now. The now() method of datetime fetches the current timestamp, but without time zone information. Such objects are called time zone-native datetime objects. The astimezone() method adds time zone information from the system local time on this time zone-naive object, essentially converting it to a time zone-aware object. (More information in The datetime object and time zones recipe). In step 3, you cast now to a string object and print it. Observe that the output date format is fixed and may not be of your choice. The datetime module has a strftime() method which can convert the object to a string in a specific format as required. In step 4, you convert now to a string in the format DD-MM-YYYY HH:MM:SS +Z. The directives used in step 4 are described as follows:

A complete list of the directives that can be given to .strptime() can be found at https://docs.python.org/3.7/library/datetime.html#strftime-and-strptime-behavior.

主站蜘蛛池模板: 孟津县| 施秉县| 郓城县| 石柱| 基隆市| 漾濞| 都兰县| 江口县| 阳江市| 哈尔滨市| 富民县| 得荣县| 金堂县| 大安市| 论坛| 佛坪县| 响水县| 弥勒县| 和林格尔县| 廊坊市| 长顺县| 广灵县| 永春县| 中宁县| 庄河市| 济宁市| 汉沽区| 曲阜市| 奉节县| 织金县| 潮安县| 红安县| 大悟县| 仙桃市| 高安市| 大埔县| 荆州市| 乐昌市| 商城县| 永安市| 建瓯市|