NumPy: Create 24 python datetime and then put it in a numpy array
NumPy DateTime: Exercise-4 with Solution
Write a NumPy program to create 24 python datetime. datetime objects (single object for every hour), and then put it in a numpy array.
Sample Solution:-
Python Code:
import numpy as np
import datetime
start = datetime.datetime(2000, 1, 1)
dt_array = np.array([start + datetime.timedelta(hours=i) for i in range(24)])
print(dt_array)
Sample Output:
[datetime.datetime(2000, 1, 1, 0, 0) datetime.datetime(2000, 1, 1, 1, 0) datetime.datetime(2000, 1, 1, 2, 0) datetime.datetime(2000, 1, 1, 3, 0) datetime.datetime(2000, 1, 1, 4, 0) datetime.datetime(2000, 1, 1, 5, 0) datetime.datetime(2000, 1, 1, 6, 0) datetime.datetime(2000, 1, 1, 7, 0) datetime.datetime(2000, 1, 1, 8, 0) datetime.datetime(2000, 1, 1, 9, 0) datetime.datetime(2000, 1, 1, 10, 0) datetime.datetime(2000, 1, 1, 11, 0) datetime.datetime(2000, 1, 1, 12, 0) datetime.datetime(2000, 1, 1, 13, 0) datetime.datetime(2000, 1, 1, 14, 0) datetime.datetime(2000, 1, 1, 15, 0) datetime.datetime(2000, 1, 1, 16, 0) datetime.datetime(2000, 1, 1, 17, 0) datetime.datetime(2000, 1, 1, 18, 0) datetime.datetime(2000, 1, 1, 19, 0) datetime.datetime(2000, 1, 1, 20, 0) datetime.datetime(2000, 1, 1, 21, 0) datetime.datetime(2000, 1, 1, 22, 0) datetime.datetime(2000, 1, 1, 23, 0)]
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a NumPy program to count the number of days of a given month.
Next: Write a NumPy program to find the first Monday in May 2017.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
F strings:
It is a common practice to add variables inside strings. F strings are by far the coolest way of doing it. To appreciate the f strings more, let's first perform the operation with the format function.
name = 'Owen' age = 25 print("{} is {} years old".format(name, age))
Output:
Owen is 25 years old
We specify the variables that go inside the curly braces by using the format function at the end. F strings allow for specifying the variables inside the string.
name = 'Owen' age = 25 print(f"{name} is {age} years old")
Output:
Owen is 25 years old
F strings are easier to follow and type. Moreover, they make the code more readable.
A, B, C = {2, 4, 6} print(A, B, C) A, B, C = ['p', 'q', 'r'] print(A, B, C)
Output:
2 4 6 p q r
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises