Python datetime conversion - python-3.x

import datetime as dt
from dateutil.tz import gettz
import time
timezone_a = "Japan"
timezone_b = "Europe/London"
unix_time = 1619238722
result = dt.datetime.fromtimestamp(unix_time, gettz(timezone_a)).strftime("%Y-%m-%d-%H-%M-%S")
print(result, timezone_a)
result = dt.datetime.fromtimestamp(unix_time, gettz(timezone_b)).strftime("%Y-%m-%d-%H-%M-%S")
print(result, timezone_b)
# This code prints
"""
2021-04-24-13-32-02 Japan
2021-04-24-05-32-02 Europe/London
I am trying to reverse it backwards so that input is
2021-04-24-13-32-02 Japan
2021-04-24-05-32-02 Europe/London
And output is 1619238722
"""
Hello, I am trying to figure out how to convert a string with a timezone into Unix time. Any help would be apreciated. Thanks!

afaik, there is no built-in method in the standard lib to parse IANA time zone names. But you can do it yourself like
from datetime import datetime
from zoneinfo import ZoneInfo # Python 3.9+
t = ["2021-04-24-13-32-02 Japan", "2021-04-24-05-32-02 Europe/London"]
# split strings into tuples of date/time + time zone
t = [elem.rsplit(' ', 1) for elem in t]
# parse first element of the resulting tuples to datetime
# add time zone (second element from tuple)
# and take unix time
unix_t = [datetime.strptime(elem[0], "%Y-%m-%d-%H-%M-%S")
.replace(tzinfo=ZoneInfo(elem[1]))
.timestamp()
for elem in t]
# unix_t
# [1619238722.0, 1619238722.0]

See if this code works.
# convert string to datetimeformat
date = datetime.datetime.strptime(date, "%Y-%m-%d-%H-%M-%S %Z")
# convert datetime to timestamp
unixtime = datetime.datetime.timestamp(date)

Related

transform timestamp (Seconds sins 1.1.1904) from NetCDF file

even there are several posts concerning NetCDF files and timestamp conversion I draw a blank today.
I
read in a NetCDF data set (version 3), and after I call variables information:
# Load required Python packages
import netCDF4 as nc
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import pandas as pd
#read in a NetCDF data set
ds = nc.Dataset(fn)
# call time variable information
print(ds['time'])
As answer I get:
<class 'netCDF4._netCDF4.Variable'>
float64 time(time)
units: seconds since 1904-01-01 00:00:00.000 00:00
long_name: time UTC
axis: T
unlimited dimensions: time
current shape = (5760,)
filling on, default _FillValue of 9.969209968386869e+36 used
Now I would like to transform the seconds since 1.1.1904 time stamp into a DD.MM.YYYY HH:MM:SS.sss format. (by the way: why is there a second 00:00 information included after the time stamp?)
(1) I tried:
t = ds['time'][:]
dtime = []
dtime = (pd.to_datetime(t, format='%d.%m.%Y %H:%M:%S.micros') - datetime(1904, 1, 1)).total_seconds()
And I get the error:
pandas_libs\tslibs\strptime.pyx in pandas._libs.tslibs.strptime.array_strptime()
time data '3730320000' does not match format '%d.%m.%Y %H:%M:%S' (match)
(2) I tried:
d = datetime.strptime("01-01-1904", "%m-%d-%Y")
dt = d + timedelta(seconds=(t))
I get the
TypeError: unsupported type for timedelta seconds component: MaskedArray
(3) I tried
d = datetime.strptime("%m-%d-%Y", "01-01-1904")
dt = d + timedelta(seconds=(ds['time']))
And I get the answer:
unsupported type for timedelta seconds component: netCDF4._netCDF4.Variable
Has somebody a clearer view on the solution than I have at the moment?
Thanks,
Swawa
The NetCDF4 python library has a method for this: num2date().
https://unidata.github.io/netcdf4-python/#num2date. No need for datetime module.
NetCDF4 variables contain metadata attributes which describe the variable as seen in the output to your print:
print(ds['time']) #In particular the time variable units attribute.
# t contains just the numeric values of the time in `seconds since 1904-01-01 00:00:00.000 00:00`
t = ds['time'][:]
dtime = []
# t_var is the NetCDF4 variable which has the `units` attribute.
t_var = ds.['time']
#dtime = (pd.to_datetime(t, format='%d.%m.%Y %H:%M:%S.micros') - datetime(1904, 1, 1)).total_seconds()
dtime = NetCDF4.num2date(t, t_var.units)
The above should give you all the times in the dtime list as datetime objects.
print(dtime[0].isoformat())
print(dtime[-1].isoformat())
A simpler way would be:
dtime = NetCDF4.num2date(ds['time'][:], ds['time].units)

Sort by datetime in python3

Looking for help on how to sort a python3 dictonary by a datetime object (as shown below, a value in the dictionary) using the timestamp below.
datetime: "2018-05-08T14:06:54-04:00"
Any help would be appreciated, spent a bit of time on this and know that to create the object I can do:
format = "%Y-%m-%dT%H:%M:%S"
# Make strptime obj from string minus the crap at the end
strpTime = datetime.datetime.strptime(ts[:-6], format)
# Create string of the pieces I want from obj
convertedTime = strpTime.strftime("%B %d %Y, %-I:%m %p")
But I'm unsure how to go about comparing that to the other values where it accounts for both day and time correctly, and cleanly.
Again, any nudges in the right direction would be greatly appreciated!
Thanks ahead of time.
Datetime instances support the usual ordering operators (< etc), so you should order in the datetime domain directly, not with strings.
Use a callable to convert your strings to timezone-aware datetime instances:
from datetime import datetime
def key(s):
fmt = "%Y-%m-%dT%H:%M:%S%z"
s = ''.join(s.rsplit(':', 1)) # remove colon from offset
return datetime.strptime(s, fmt)
This key func can be used to correctly sort values:
>>> data = {'s1': "2018-05-08T14:06:54-04:00", 's2': "2018-05-08T14:05:54-04:00"}
>>> sorted(data.values(), key=key)
['2018-05-08T14:05:54-04:00', '2018-05-08T14:06:54-04:00']
>>> sorted(data.items(), key=lambda item: key(item[1]))
[('s2', '2018-05-08T14:05:54-04:00'), ('s1', '2018-05-08T14:06:54-04:00')]

datetime converting format in python

have list of an other lists that contains date (y,m,d h,m,s,ms), and an other list of some values. I would plot this values in function of date but I couldn't convert the first list on date. How can I do this?
import datetime
import matplotlib
from time import mktime
import datetime as dt
from datetime import datetime
date = [
['"2017/10/27"', '"08:18:12"', ' 0.400'],
['"2017/10/27"', '"08:18:12"', ' 0.500'],
['"2017/10/27"', '"08:18:12"', ' 0.600']
]
values = [2,4,5]
for i in range(len(date)):
date[i][0] = eval(date[i][0])
date[i][1] = eval(date[i][1])
date[i][2] = date[i][2].strip()
date = [' '.join(elem) for elem in date]
>>>['2017/10/27 08:18:12 0.400', '2017/10/27 08:18:12 0.500', '2017/10/27
08:18:12 0.600']
date = [mktime(datetime.strptime(elem,'%Y-%m-%d %H:%M:%S
0.%f').timetuple()) for elem in date]
>>ValueError: time data '2017/10/27 08:18:12 0.400' does not match format
'%Y-%m-%d %H:%M:%S 0.%f
I have lists of thousands of lines so if some could this more efficiently I'll be very grateful. thank you in advance.
Your error message actually tells you exactly what's wrong :) The python function you're using, does pattern matching to find the different elements (minutes, hours, etc) in your time string.
You're using:
date = [mktime(datetime.strptime(elem,'%Y-%m-%d %H:%M:%S 0.%f').timetuple()) for elem in date]
but your time string is '2017/10/27 08:18:12 0.400'. You're using / and not - as a separator, so the function above can't find a matching string. Change your code above to:
date = [mktime(datetime.strptime(elem,'%Y/%m/%d %H:%M:%S 0.%f').timetuple()) for elem in date]

Change default dateparcer output

I found dateparser as a great way to change natural language into dates. Now, I am trying to manipulate the output of the parser without success.
from dateparser import parse
import datetime
def pars():
n = "in two days"
x = parse(n, settings={'TIMEZONE': 'US/Eastern'})
print (x)
>>> 2016-08-25 00:18:03.268506
t = datetime.datetime(x)
t.strftime('%m/%d/%Y')
print (t)
pars()
I get the error: TypeError: an integer is required (got type datetime.datetime)
Many things are wrong with the code.
dateparser returns datetime.datetime objects not some ints that is what datetime.datetime expects
strftime does not update the datetime.datetime object in place, if you want to keep the string value it produces, assign it to some var.
def pars():
x = parse('in two days')
t = x.strftime('%m/%d/%Y')
print 'datetime', x
print 'strftime', t
>>> pars()
datetime 2016-09-30 23:34:07.863881
strftime 09/30/2016

Passing parameters to strftime method

I'm new to python. my question is how to pass parameter to date.strftime() or a workaround
Below is the code
from datetime import date
dl_date = date.today()
p = '%d%b%Y' # the format may vary %d%B%Y or %d%m%Y or % d%M%Y etc
file_date_format = "{0}/{1}/{2}".format(str(dl_date.strftime('%r')),str(dl_date.strftime('%r').upper())
, str(dl_date.strftime('%r'))) % (p[:2], p[2:4], p[4:6])
print(file_date_format)
Help is much appreciated.
No need to use percent style string formatting here. Just stick the p slices directly in the strftime calls.
from datetime import date
dl_date = date.today()
p = '%d%b%Y' # the format may vary %d%B%Y or %d%m%Y or % d%M%Y etc
file_date_format = "{0}/{1}/{2}".format(
str(dl_date.strftime(p[:2])),
str(dl_date.strftime(p[2:4]).upper()),
str(dl_date.strftime(p[4:6]))
)
print(file_date_format)
Result:
14/NOV/2014

Resources