Saturday, December 25, 2021

date time in python

 # ========================================================================

# date time using python

# ========================================================================


#uncomment to import library 

import pandas as pd 

import datetime as dt


#converting string into datetime 

df1 = pd.DataFrame(

     {

      "DateTime": pd.to_datetime(["2021-11-13 13:45:33",

                                  '2021-11-14 14:13:25',

                                  "2021-11-15 14:39:25", 

                                  "2021-11-16 15:16:43", 

                                  "2021-11-17 16:51:19"]),

     }

)


#split datetime into individual date and time df column

df1['Dates'] = pd.to_datetime(df1['DateTime']).dt.date

df1['Time'] = pd.to_datetime(df1['DateTime']).dt.time


#join date and time columns into a datetime column 

df1['DateTime_join'] = pd.DataFrame(

    pd.to_datetime(df1['Dates'].astype(str) + ' ' + df1['Time'].astype(str)), 

    columns=['Datetime_join']) 

print(df1)



# ========================================================================

# date time format change

# ========================================================================

import pandas as pd

dt = "02-11-2021"

dt1 = pd.to_datetime(dt)

dt1

#output# Timestamp('2021-02-11 00:00:00')

dt2 = pd.to_datetime(dt, format = "%d-%m-%Y")

dt2

#output# Timestamp('2021-11-02 00:00:00')



# ========================================================================

# date time format

# ========================================================================


import pandas as pd

dt = pd.to_datetime("02-11-2021")

dt3 = dt.strftime('%b/%d/%Y')

dt3

#output# 'Feb/11/2021'



python class topic video