Search code examples
pythonpandastimezonedjango-timezone

UnknownTimeZoneError in Pandas.Timestamp.now


I want to append the Timestamp of current time for my timezone, but don't know where to find the correct value of my timezone. Apparently, it's Islamabad/Karachi, but no success.

Here is my small code chunk

import pandas as pd
...
#df -> a dataframe
df.to_csv('C:/path/to/file-'+str(pd.Timestamp.now())+'.tsv', mode='a', index=None, sep='\t', header=False)

Desired output file name is

file-10;17;52--29-06-2020 for file-hour;minutes;sec--day-month-year

I know : is not allowed in names


Solution

  • IF you are in the required TimeZone, then simply doing the below will work;

    from datetime import datetime
    time_now = datetime.now() # Will give your local time
    

    OR,

    We can get the same by shifting the UTC time by let's say by 5 hours

    from datetime import datetime, timezone, timedelta
    now_utc = datetime.utcnow() # Current time in UTC
    my_tz_time = now_utc + timedelta(hours=5) # now we can shift the time by 5 hours easily
    

    EDIT -1

    Based on the link shared by @MrFuppes, in the second approach, we should do the below,

    from datetime import datetime, timezone, timedelta
    now_utc = datetime.now(tz=timezone.utc) # Time in UTC
    my_tz_time = now_utc + timedelta(hours=5) # now we can shift the time by 5 hours easily