- Python Algorithmic Trading Cookbook
- Pushpak Dagade
- 325字
- 2021-06-11 18:29:20
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:
- Import the necessary modules from the Python standard library:
>>> from datetime import datetime
- Fetch the current timestamp along with time zone information. Assign it to now and print it:
>>> now = datetime.now().astimezone()
- 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
- 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.
- 數據展現的藝術
- Mastering Mesos
- 自動控制工程設計入門
- Mastering Matplotlib 2.x
- Hands-On Artificial Intelligence on Amazon Web Services
- 輕松學Java Web開發
- Practical Data Wrangling
- 數據挖掘實用案例分析
- Windows XP中文版應用基礎
- 機器自動化控制器原理與應用
- Machine Learning with the Elastic Stack
- 網絡安全技術及應用
- SMS 2003部署與操作深入指南
- 水晶石影視動畫精粹:After Effects & Nuke 影視后期合成
- 計算機組成與操作系統