Converting epoch to human-readable date doesn't work in python - python

I am using time module to convert epoch into human readable date using the code below.
import time
datetime = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(1609740000000))
print(datetime)
>>> Thu, 17 Aug 52980 20:00:00 +0000
The output is incorrect when I check it on https://www.epochconverter.com
Correct output should be Wed, 04 Aug 2021 21:49:24 +0000

time.localtime takes time in seconds. You presumably pass time in milliseconds.
datetime = time.strftime("%a, %d %b %Y %H:%M:%S +0000",
time.localtime(1609740000000 // 1000))
#'Mon, 04 Jan 2021 01:00:00 +0000'
The answer from epochconverter.com is the same. Your "correct output" is incorrect.

Related

How to convert this time format 'Fri Apr 01 2022 00:01:00 GMT+0100' to UTC/GMT

I'm converting this time format Fri Apr 01 2022 00:01:00 GMT+0100 like this
date_parser = lambda x: datetime.strptime(x, "%a, %d %b %Y %H:%M:%S %Z")
ch = pd.read_excel(
r'ACEOM2022-04_2022-07.xlsx',
skiprows=[1],
dtype{'datetime':str},
parse_dates=["datetime"],
date_parser=date_parser
)
But I would like to convert this datetime Fri Apr 01 2022 00:01:00 GMT+0100 into the same above format.
I have one more dataframe which is in UTC format.
I would like to have all the dataframes to be in UTC itself.
How can I do it in python so that all the data is in a same format? Please do provide your response.

Parse Datetime with +0 timezone

I have the following Datetime string: Dec 03 2020 01: +0 which I want to parse into a datetime object.
dtObj = datetime.strptime("Dec 03 2020 01: +0", '%b %d %Y %I: %z')
Checking the Documentation, this should work but I get the following error:
ValueError: time data 'Dec 03 2020 01: +0' does not match format '%b %d %Y %I: %z'
Any ideas what I have overseen?
Thanks in advance
Any ideas what I have overseen?
strftime.org claims that %z
UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object
is naive).
this mean that it must contain at least 4 digits after + or - (HHMM part, which is compulsory), taking this is account Dec 03 2020 01: +0 is not compliant with used format string, whilst Dec 03 2020 01: +0000 is
import datetime
dtObj = datetime.datetime.strptime("Dec 03 2020 01: +0000", '%b %d %Y %I: %z')
print(dtObj)
gives output
2020-12-03 01:00:00+00:00

How to parse Fri, 25 Jun 2021 12:06:16 +0000 (UTC) to datetime object?

If there was no (UTC), it would be:
%a, %d %b %Y %X %z
but server is sending with additional (UTC) or (CDT) how do you parse it?
%a, %d %b %Y %X %z (%Z) doesn't work.
How does it not work? Which version of python are you using?
I just ran the following in python 3.9:
datetime.datetime.strptime("Fri, 25 Jun 2021 12:06:16 +0000 (UTC)", "%a, %d %b %Y %X %z (%Z)")
Which created this datetime object:
datetime.datetime(2021, 6, 25, 12, 6, 16, tzinfo=datetime.timezone(datetime.timedelta(0), 'UTC'))

Python Code to convert Wed, 06 Feb 2019 20:47:46 GMT to 2019-02-06 15:47:46 EST or EDT

I am trying to convert GMT time to EST/EDT format in Python.
GMT Format: Wed, 06 Feb 2019 20:47:46 GMT
Required Format: 2019-02-06 15:47:46 EST (when daylight time starts it should be EDT)
I need this without doing any additional pip install.
Currently, I am using below code which is giving EST time as : 2019-02-06 15:47:46-05:00
import datetime
from datetime import datetime
from dateutil import tz
enable_date = response["ResponseMetadata"]["HTTPHeaders"]["date"]
print "Enable Date in GMT: {0}".format(enable_date)
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('US/Eastern')
utc = datetime.strptime(enable_date, '%a, %d %b %Y %H:%M:%S GMT')
utc = utc.replace(tzinfo=from_zone)
central = utc.astimezone(to_zone)
print "Enable Date in EST: {0}".format(central)
output:
Enable Date in GMT: Wed, 06 Feb 2019 20:47:46 GMT
Enable Date in EST: 2019-02-06 15:47:46-05:00
desired output:
Enable Date in EST: 2019-02-06 15:47:46 EST
Variable enable_date has value Wed, 06 Feb 2019 20:47:46 GMT
gmt_date = "Thu, 07 Feb 2019 15:33:28 GMT"
def date_convert():
print "Date in GMT: {0}".format(gmt_date)
# Hardcode from and to time zones
from_zone = tz.gettz('GMT')
to_zone = tz.gettz('US/Eastern')
# gmt = datetime.gmtnow()
gmt = datetime.strptime(gmt_date, '%a, %d %b %Y %H:%M:%S GMT')
# Tell the datetime object that it's in GMT time zone
gmt = gmt.replace(tzinfo=from_zone)
# Convert time zone
eastern_time = str(gmt.astimezone(to_zone))
# Check if its EST or EDT
if eastern_time[-6:] == "-05:00":
print "Date in US/Eastern: " +eastern_time.replace("-05:00"," EST")
elif eastern_time[-6:] == "-04:00":
print "Date in US/Eastern: " +eastern_time.replace("-04:00"," EDT")
return
Last line should be
print "Enable Date in EST: {0}".format(central.strftime('%Y-%m-%d %H:%M:%S %Z'))

error reading date time from csv using pandas

I am using Pandas to read and process csv file. My csv file have date/time column that looks like:
11:59:50:322 02 10 2015 -0400 EDT
11:11:55:051 16 10 2015 -0400 EDT
00:38:37:106 02 11 2015 -0500 EST
04:15:51:600 14 11 2015 -0500 EST
04:15:51:600 14 11 2015 -0500 EST
13:43:28:540 28 11 2015 -0500 EST
09:24:12:723 14 12 2015 -0500 EST
13:28:12:346 28 12 2015 -0500 EST
How can I read this using python/pandas, so far what I have is this:
pd.to_datetime(pd.Series(df['senseStartTime']),format='%H:%M:%S:%f %d %m %Y %z %Z')
But this is not working, though previously I was able to use the same code for another format (with a different format specifier). Any suggestions?
The issue you're having is likely because versions of Python before 3.2 (I think?) had a lot of trouble with time zones, so your format string might be screwing up on the %z and %Z parts. For example, in Python 2.7:
In [187]: import datetime
In [188]: datetime.datetime.strptime('11:59:50:322 02 10 2015 -0400 EDT', '%H:%M:%S:%f %d %m %Y %z %Z')
ValueError: 'z' is a bad directive in format '%H:%M:%S:%f %d %m %Y %z %Z'
You're using pd.to_datetime instead of datetime.datetime.strptime but the underlying issues are the same, you can refer to this thread for help. What I would suggest is instead of using pd.to_datetime, do something like
In [191]: import dateutil
In [192]: dateutil.parser.parse('11:59:50.322 02 10 2015 -0400')
Out[192]: datetime.datetime(2015, 2, 10, 11, 59, 50, 322000, tzinfo=tzoffset(None, -14400))
It should be pretty simple to chop off the timezone at the end (which is redundant since you have the offset), and change the ":" to "." between the seconds and microseconds.
Since datetime.timezone has become available in Python 3.2, you can use %z with .strptime() (see docs). Starting with:
dateparse = lambda x: pd.datetime.strptime(x, '%H:%M:%S:%f %d %m %Y %z %Z')
df = pd.read_csv(path, parse_dates=['time_col'], date_parser=dateparse)
to get:
time_col
0 2015-10-02 11:59:50.322000-04:00
1 2015-10-16 11:11:55.051000-04:00
2 2015-11-02 00:38:37.106000-05:00
3 2015-11-14 04:15:51.600000-05:00
4 2015-11-14 04:15:51.600000-05:00
5 2015-11-28 13:43:28.540000-05:00
6 2015-12-14 09:24:12.723000-05:00
7 2015-12-28 13:28:12.346000-05:00

Categories

Resources