Struggling to convert timezones GMT to CST in Python - python

I've spent hours on this, but my brain can't seem to figure it out, and it seems a lot of info I've found applies to Python 2?
import datetime as dt
from datetime import datetime
from pytz import timezone
import pytz
time_stamp = 'Mon, 17 Dec 2018 18:05:01 GMT'
central = timezone('US/Central')
published_time = datetime.strptime(time_stamp, '%a, %d %b %Y %H:%M:%S %Z')
published_cst = published_time.astimezone(central)
actual_time_published = published_cst.strftime('%a, %b %d %Y at %I:%M:%S %p %Z')
print(time_stamp)
print(published_time)
print(published_cst)
print(actual_time_published)
Expecting acutal_time_published to be CST because published_cst has GMT-6 hours (third result), but here is the actual result for each print command.
Mon, 17 Dec 2018 18:05:01 GMT
2018-12-17 18:05:01
2018-12-17 18:05:01-06:00
Mon, Dec 17 2018 at 06:05:01 PM CST
Pulling my hair out!
EDIT: Yes, I had "entry.published" where I meant to put "time_stamp" for the purposes of this question. Thanks for the edit!

I figured it out! Even though the original time stamp was returning a timezone (GMT), it did not have a tzinfo value (timezone value) assigned to it. It was still a "naive" datetime, even though the string contained a timezone recognized by strptime. So, I just assigned a tzinfo value of UTC to the original time and it seemed to fix it.
time_stamp = 'Mon, 17 Dec 2018 18:05:01 GMT'
utc = timezone('UTC')
central = timezone('US/Central')
published_time = datetime.strptime(time_stamp, '%a, %d %b %Y %H:%M:%S %Z')
published_gmt = published_time.replace(tzinfo=utc)
published_cst = published_gmt.astimezone(central)
actual_time_published = published_cst.strftime('%a, %b %d %Y at %I:%M:%S %p %Z')
So...
print(time_stamp)
print(published_time)
print(published_cst)
print(actual_time_published)
Yeilds this output:
Mon, 17 Dec 2018 18:05:01 GMT
2018-12-17 18:05:01
2018-12-17 18:05:01+00:00
2018-12-17 12:05:01-06:00
Mon, Dec 17 2018 at 12:05:01 PM CST

Related

Timezone in python date string is not matching

In a script, I am converting the date string into DateTime format, so that I can modify the date, but this timezone part is showing an error.
from datetime import datetime
date_str = 'Wed, 1 Jun 2022 16:44:40 +0200 (CEST)'
temp_date = datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S %z (%Z)')
print(temp_date)
When I run this I am getting ValueEror.
ValueError: time data 'Wed, 01 Jun 2022 16:44:40 +0200 (CEST)' does not match format '%a, %d %b %Y %H:%M:%S %z (%Z)'
An extract from the datetime documentation:
strptime() only accepts certain values for %Z:
any value in time.tzname for your machine’s locale
the hard-coded values UTC and GMT
So someone living in Japan may have JST, UTC, and GMT as valid values,
but probably not EST. It will raise ValueError for invalid values
Try running the below to see if CEST is in your machine's locale:
import time
print(time.tzname)
Seeing the complexity of problem, I suggest using third party library like dateutil which can parse datetime with ease.
from dateutil.parser import parse
date_str = 'Wed, 1 Jun 2022 16:44:40 +0200 (CEST)'
temp_date = parse(date_str)
print(temp_date)
temp_date is of type datetime.datetime
https://dateutil.readthedocs.io/en/stable/

ValueError: time data 'Tue, 19 Nov 2019 09:00 EST' does not match format '%a, %d %b %Y %H:%M %Z'

So the title is quite self explanatory: I was trying to datetime.strptime(news.date, '%a, %d %b %Y %H:%M %Z') and it didn't work out for Tue, 19 Nov 2019 09:00 EST but got a ValueError. I tried to use datetime.strptime(news.date[:-4], '%a, %d %b %Y %H:%M') and it all works just fine. How do I fix this timezone issue?
Update: the timezone will be used later, so I do need to process it as well

How to create date timestamp logs like git log

Using datetime.datetime.now(), I receive some badly formatted timestamps.
Is there an intuitive way of creating a date timestamp in this format?
Wed Aug 7 13:38:59 2019 -0500
This is seen in git log.
You can use datetime.datetime.strftime() to format dates as shown below:
from datetime import datetime
d = '2019-08-07 13:38:59-0500'
d2 = datetime.strptime(d, '%Y-%m-%d %H:%M:%S%z')
d3 = d2.strftime('%a %b %d %H:%M:%S %Y %z')
print(d3)
This returns:
Wed Aug 07 13:38:59 2019 -050000
This website is a great resource for strftime formatting.
You can still use the datetime library. Using strftime, you can rewrite the datetime object into a nicely formatted string.
In your case, you are going for Wed Aug 7 13:38:59 2019 -0500, which translated to strftime formatting is "%a %b %d %H:%M:%S %Y %z".
Overall, it'd be
datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Y %z")
Which will give a string that looks like 'Wed Aug 7 13:38:59 2019 -0500'.
I would do the following:
from time import gmtime, strftime
if __name__ == "__main__":
time = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
print(time)
This was found on the documentation page of the time module. There are also a lot of additional features you might be interested in using outlined here: https://docs.python.org/3/library/time.html#time.strftime

Converting from unix time string to python date type, Does not convert when CDT is present

I have a date time string in this format in python
"Wed Mar 20 00:52:54 CDT 2019 20 Mar 2019"
I am trying to convert this to python date time format using below code
datetime.datetime.strptime('Wed Mar 20 00:52:54 CDT 2019', "%a %b %d %H:%M:%S %Y")
But it gives error as CDT is present in the text. How to handle this problem. I am not sure if CDT will be present for all dates. In both cases i want to convert.
My requirement is only to get the difference in days between this date and now
Use CDT in the format, then calculate the difference between now and that date. Finally print delta.days.
from datetime import datetime
date0 = datetime.strptime('Wed Mar 20 00:52:54 CDT 2019', "%a %b %d %H:%M:%S CDT %Y")
date_now = datetime.now()
delta = date_now - date0
print(delta.days)
Output in this case:
0
If you're not sure if there will be CDT, check the string before passing it to strptime. Or use try/except:
try:
date0 = datetime.strptime(string, "%a %b %d %H:%M:%S CDT %Y")
except ValueError:
date0 = datetime.strptime(string, "%a %b %d %H:%M:%S %Y")

How to convert GMT time to string time

How to convert GMT time to string time? it's quite strange, when I print the time in back-end, the time is in string time format, but when I transfer it to the front-end via JSON file, the time has changed to GMT format. Why? Could someone help me?
Input: Wed, 25 Jul 2018 19:19:42 GMT
Output: 2018-07-25 19:19:42
When you convert the original time to JSON Format, it will be changed to GMT Time format. To solve this problem, you can change the time to string before converting it to JSON.
You could do something like -
from datetime import datetime
ip = 'Wed, 25 Jul 2018 19:19:42 GMT'
op = datetime.strftime(datetime.strptime(ip,'%a, %d %b %Y %H:%M:%S %Z'), '%Y-%m-%d %H:%M:%S')
# op 2018-07-25 19:19:42
Refer to this beautiful table here to get the formats right and then look into strftime and strptime
You can find resources here on strptime
from datetime import datetime
t = 'Wed, 25 Jul 2018 19:19:42 GMT'
datetime.strptime(t,'%a, %d %b %Y %H:%M:%S %Z')
datetime.datetime(2018, 7, 25, 19, 19, 42)

Categories

Resources