Reader small image

You're reading from  Python Algorithmic Trading Cookbook

Product typeBook
Published inAug 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838989354
Edition1st Edition
Languages
Right arrow
Author (1)
Pushpak Dagade
Pushpak Dagade
author image
Pushpak Dagade

Pushpak Dagade is working in the area of algorithmic trading with Python for more than 3 years. He is a co-founder and CEO of AlgoBulls, an algorithmic trading platform.
Read more about Pushpak Dagade

Right arrow

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...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Python Algorithmic Trading Cookbook
Published in: Aug 2020Publisher: PacktISBN-13: 9781838989354

Author (1)

author image
Pushpak Dagade

Pushpak Dagade is working in the area of algorithmic trading with Python for more than 3 years. He is a co-founder and CEO of AlgoBulls, an algorithmic trading platform.
Read more about Pushpak Dagade