Time¶
Here, we explain two time-related modules in Python.
datetime module¶
The datetime module provide functions to work with the date format, which they can be used to maniuplate and parsing a dates and time.
import datetime
todays_date = datetime.date.today()
print(todays_date)
now = datetime.datetime.now()
print(now)
You can a general date object to represents a date (year, month and day).
You can a general time object to represents a time (hour, minute, second and microsecond).
In a general you can you datetime object,
dtm = datetime.datetime(2024, 1, 2,12,3,4,5)
print(dtm)
print(dtm.year,dtm.month,dtm.day,dtm.hour,dtm.minute,dtm.second,dtm.microsecond)
You can change the structure of time, using strftime; US format mm/dd/yyyy, UK's format dd/mm/yyyy
date_string = "25 January, 2024"
date_string
date_object = datetime.datetime.strptime(date_string, "%d %B, %Y")
date_object
You can find different between time,
now_dtm = datetime.datetime.now()
dtm = datetime.datetime(2024, 1, 2,12,3,4,5)
diff_dtm = now_dtm - dtm
diff_dtm
print(diff_dtm)
diff_dtm.total_seconds() You can handle the timezone in Python,
import pytz
now_dtm = datetime.datetime.now()
tz_NY = pytz.timezone('America/New_York')
datetime_NY = datetime.datetime.now(tz_NY)
print("Local:", now_dtm)
print("NY:", datetime_NY)
numerial format¶
timestamp¶
A unix timestamp is the number of second between a particular date and January 1, 1970, at UTC. You can convert date to the timestamp() method.
You can convert a timestamp to a date using the fromtimestamp() method.
ordinal¶
Other approach to work with number instead data forma is to us the proleptic Gregorian ordinal of the date, where January 1 of year 1 is 1.
and back:
Panda date¶
import numpy as np
import pandas as pd
X1=["2023-1-1","2023-2-1","2023-3-1","2023-4-1"]
X2=[10,11,12,13]
raw_data = {'X1': X1,'X2': X2}
df=pd.DataFrame(raw_data)
df
To work on read data let consider Dow Jones Index:
dow_jones = pd.read_csv('data/dow_jones_index/dow_jones_index.data')
dow_jones.head(20)
dow_jones.info()
Select 'stock','date','open','high','low'
Assign week number as index
Apply the function to_week on the column data
dow_jones['week']=dow_jones['date'].apply(to_week)
dow_jones = dow_jones.set_index('week')
dow_jones=dow_jones.drop(['date'], axis=1)
Drop doller sign from columns and change them to numeric
Compute the mean for each week:
time module¶
The time module provide various time-related function for time access, to get the current time:
Pause the execution of a program for two seconds:
You can create a simple code to check running time.
import time
start_time = time.time()
some code
print("--- %s seconds ---" % (time.time() - start_time))
timeit is a module to check running of small code.