Magic ETL

Magic ETL

Convert Timestamp to CST, UST, MST, EST Python

I have a data set like the following:

  1. start_time_UTC
  2. 2021-09-16T12:00:00-05:00
  3. 2021-09-15T19:00:00-05:00
  4. 2021-09-16T08:18:00-05:00
  5. 2021-09-16T12:22:10-05:00

My default time is UTC, but I would like to create multiple columns based of the start_time_UTC to create cst, mst, and est.

  1. from domomagic import *
  2. from datetime import datetime as dt
  3. import pandas as pd
  4. from pytz import timezone
  5. import pytz
  6. df = read_dataframe('my_dataset')
  7. df['time_stamp'] = df['start_time']
  8. utc = timezone('UTC')
  9. cst = timezone('US/Central')
  10. mst = timezone('US/Mountain')
  11. est = timezone('US/Eastern')
  12.  
  13. # my issue begins at 'published_time"
  14. published_time = time_stamp.apply(lambda x: dt.strptime(df.time_stamp, '%a, %d %b %Y %H:%M:%S %Z'))
  15. time_utc = published_time.replace(tzinfo=utc)
  16. time_cst = published_time.replace(tzinfo=cst)
  17. time_mst = published_time.replace(tzinfo=mst)
  18. time_est = published_time.replace(tzinfo=est)
  19. # then call using time_timezone
  20. df['time_published_cst'] = time_cst.strftime('%I:%M:%S %p %Z')
  21. df['time_published_est'] = time_est.strftime('%I:%M:%S %p %Z')
  22. df['time_published_mst'] = time_mst.strftime('%I:%M:%S %p %Z')
  23. df['time_published_utc'] = time_utc.strftime('%I:%M:%S %p %Z')

Initially I received an error for the following that said, "TypeError: strptime() argument 1 must be str, not Series":

  1. published_time = datetime.strptime(time_stamp, '%a, %d %b %Y %H:%M:%S %Z')

So, I changed it using lambda but got an error saying, " NameError: name 'time_stamp' is not defined"

  1. published_time = time_stamp.apply(lambda x: dt.strptime(df.time_stamp, '%a, %d %b %Y %H:%M:%S %Z'))

Then again I tried the following but got an error that said, 'time_stamp' does not match format '%a, %d %b %Y %H:%M:%S %Z'

  1. published_time = df['time_stamp'].apply(lambda x: dt.strptime('time_stamp', '%a, %d %b %Y %H:%M:%S %Z'))

Can anyone tell me what I could be wrong?

Tagged:

Welcome!

It looks like you're new here. Members get access to exclusive content, events, rewards, and more. Sign in or register to get started.
Sign In

Answers

Welcome!

It looks like you're new here. Members get access to exclusive content, events, rewards, and more. Sign in or register to get started.
Sign In