Search code examples
pythonpandastimestamp-with-timezone

Adding Asia/Singapore Time stamp as the first column in Pandas dataframe


I am trying to add an Asia/Singapore timestamp as the first column of the following pandas dataframe,and name it as 'sdc_sequence_id'.

id   col1    col2
01    A       B
02    C       D
03    E       F

expected dataframe :

sdc_sqeuence_id       id     col1    col2
2002-10-27 12:00:00   01      A      B
2002-10-27 12:00:02   02      C      D
2002-10-27 12:00:02   03      E      F

I tried doing this

df2['sdc_squence_id'] = df2['sdc_squence_id'].dt.tz_localize('Asia/Singapore'

But this is giving me a key error.. Help would be appreciated.


Solution

  • Try:

    df["sdc_squence_id"] = datetime.strftime(datetime.now(pytz.timezone('Asia/Singapore')), "%Y-%m-%d %H:%M:%S")
    

    Explanations:

    1. Get the local time in a specific timezone:
      • Use the pytz to get timezone:
    tz = pytz.timezone('Asia/Singapore')
    
    • This discussion explains in details how to get local time
    asia_time = datetime.now(tz)
    
    1. Format local time as you want:
    formated_datetime = datetime.strftime(asia_time, "%Y-%m-%d %H:%M:%S")
    
    1. Add the new column to the panda dataframe:
    df["sdc_squence_id"] = formated_datetime
    

    Code

    # Import modules
    import pandas as pd
    # Get local timezone time
    import pytz
    # Create datetime object
    from datetime import datetime
    
    
    tz = pytz.timezone('Asia/Singapore')
    print(tz)
    # Asia/Singapore
    
    asia_time = datetime.now(tz)
    print(asia_time)
    # 2020-03-24 17:22:37.409483+08:00
    
    # Format datetime
    formated_datetime = datetime.strftime(asia_time, "%Y-%m-%d %H:%M:%S")
    # 2020-03-24 17:22:37
    
    # Create new column
    df["sdc_squence_id"] = formated_datetime
    print(df)
    #    id col1 col2       sdc_squence_id
    # 0   1    A    B  2020-03-24 17:22:37
    # 1   2    C    D  2020-03-24 17:22:37
    # 2   3    E    F  2020-03-24 17:22:37