datetime to string with time zone
Use the "zzz" format specifier to get the UTC offset. For example:
var dt = new DateTime(2010, 1, 1, 1, 1, 1, DateTimeKind.Utc);
string s = dt.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss \"GMT\"zzz");
Console.WriteLine(s);
Output:
2009-12-31 19:01:01 GMT-06:00
I'm in the CDT timezone. Make sure the DateTime is unambiguously DateTimeKind.Utc.
How to convert a timezone aware string to datetime in Python without dateutil?
As of Python 3.7, datetime.datetime.fromisoformat()
can handle your format:
>>> import datetime
>>> datetime.datetime.fromisoformat('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
In older Python versions you can't, not without a whole lot of painstaking manual timezone defining.
Python does not include a timezone database, because it would be outdated too quickly. Instead, Python relies on external libraries, which can have a far faster release cycle, to provide properly configured timezones for you.
As a side-effect, this means that timezone parsing also needs to be an external library. If dateutil
is too heavy-weight for you, use iso8601
instead, it'll parse your specific format just fine:
>>> import iso8601
>>> iso8601.parse_date('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=<FixedOffset '-04:00'>)
iso8601
is a whopping 4KB small. Compare that tot python-dateutil
's 148KB.
As of Python 3.2 Python can handle simple offset-based timezones, and %z
will parse -hhmm
and +hhmm
timezone offsets in a timestamp. That means that for a ISO 8601 timestamp you'd have to remove the :
in the timezone:
>>> from datetime import datetime
>>> iso_ts = '2012-11-01T04:16:13-04:00'
>>> datetime.strptime(''.join(iso_ts.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))
The lack of proper ISO 8601 parsing is being tracked in Python issue 15873.
Convert datetime to string always defaults to system time zone offset, Need to get the users timezone offset in the result
You can use DateTimeOffset
instead of DateTime
to handle this:
DateTimeOffset time = DateTime.Now;
string timezoneID = "Pacific Standard Time";
TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById(timezoneID);
DateTimeOffset newTIme = TimeZoneInfo.ConvertTime(time, info);
string timeformat = newTIme.ToString("yyyy-MM-dd HH:mm:ss \"GMT\"zzz");
string oldtimeformat = time.ToString("yyyy-MM-dd HH:mm:ss \"GMT\"zzz");
convert python datetime with timezone to string
The way you seem to be doing it, would work fine for both timezone aware and naive datetime objects. If you want to also add the timezone to your string, you can simply add add it with %z or %Z, or using the isoformat
method:
>>> from datetime import timedelta, datetime, tzinfo
>>> class UTC(tzinfo):
... def utcoffset(self, dt):
... return timedelta(0)
...
... def dst(self, dt):
... return timedelta(0)
...
... def tzname(self,dt):
... return "UTC"
>>> source = datetime(2010, 7, 1, 0, 0, tzinfo=UTC())
>>> repr(source)
datetime.datetime(2010, 7, 1, 0, 0, tzinfo=<__main__.UTC object at 0x1054107d0>)
# %Z outputs the tzname
>>> source.strftime("%Y-%m-%d %H:%M:%S %Z")
'2010-07-01 00:00:00 UTC'
# %z outputs the UTC offset in the form +HHMM or -HHMM
>>> source.strftime("%Y-%m-%d %H:%M:%S %z")
'2010-07-01 00:00:00 +0000'
# isoformat outputs the offset as +HH:MM or -HH:MM
>>> source.isoformat()
'2010-07-01T00:00:00+00:00'
Java Date Time conversion to given timezone
with the help of @ole v.v's explanation i have separated the datetime value for two
1. time
2. timezone
then i used this coding to extract the datetime which is related to the given timezone
//convert datetime to give timezone
private static String DateTimeConverter (String timeVal, String timeZone)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat offsetDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
offsetDateFormat2.setTimeZone(TimeZone.getTimeZone(timeZone));
String result =null;
try {
result = offsetDateFormat2.format(format.parse(timeVal));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
How to format datetime based on timezone dynamically
finally, I figured out. I posted it for anyone if having same issue.
I also need to import kendo package.
import '@progress/kendo-date-math/tz/all';
import { IntlService } from "@progress/kendo-angular-intl"
then will get result from
const from: Date = ZonedDate.fromLocalDate(new Date(dateTime), zone);
return this.intl.formatDate(from, "dd/MM/yyyy hh:mm a")
Convert String to DateTime Object in specific timezone with Powershell
To treat a given nominal date (one that is unspecified with respect to what time zone it relates to) as one in the EST (US Eastern Standard Time) time zone:
That is, convert a date string such as '2020-01-24 03:00:57'
into
a [datetimeoffset]
instance that represents this unspecified-in-terms-of-time-zone string as a date/time local to the EST (Eastern Standard Time) time zone (possibly with DST (daylight-saving time) offset applied), which can then be formatted in a ISO 8601 format that includes the resulting date's specific UTC offset.
# Construct a nominal [datetime] instance whose .Kind property value is
# Unspecified (which means unspecified with respect to any particular
# time zone), which a cast from a string achieves:
$nominalDate = [datetime] '2020-01-24 03:00:57'
# Determine the target time zone.
# Note: On macOS and Linux, use 'America/New_York' (ICU library IDs).
$tz = [TimeZoneInfo]::FindSystemTimeZoneById('Eastern Standard Time')
# Get the UTC offset for the nominal date (.Kind == Unspecified),
# which is interpreted as local to that time zone.
# The offset is returned as a [timespan] instance that properly reflects
# DST, if the date falls into the DST window of the target time zone.
# If the input date is ambiguous or invalid, standard time is assumed.
$utcOffset = $tz.GetUtcOffset($nominalDate)
# Construct a [datetimeoffset] instance with the UTC offset determined above.
# This in effect creates a date that represents the nominal date in the
# target time zone, using that time zone's DST-appropriate UTC offset.
$dto = [DateTimeOffset]::new($nominalDate.Ticks, $utcOffset)
# Format according to ISO 8601 with UTC offset, but remove the
# fractional-seconds part:
# Note: With the standar "o" format specifier, only [datetimeoffset]
# instances include their UTC offset in the resulting string,
# not [datetime] instances.
$dto.ToString('o') -replace '\.\d+(?=-)'
The above yields '2020-01-24T03:00:57-05:00'
, as desired.
With a DST-window input date such as '2020-07-24 03:00:57'
, it would yield'2020-07-24T03:00:57-04:00'
- note how the UTC offset is now one hour less.
See also: The System.DateTime
([datetime]
, as a PowerShell type literal), System.DateTimeOffset
([datetimeoffset]
), and System.TimeZoneInfo
([TimeZoneInfo]
) types, and Standard date and time format strings.
The following is a related use case with a different premise:
To translate a given local date into its EST equivalent:
That is, translate a local point in time, such as obtained by Get-Date
, into the equivalent time in the EST time zone.
# Start with a local date, in any time zone.
# (A [datetime] instance whose .Kind property value is Local, though
# Unspecified would work the same).
# Alternatively, start with a UTC date (where .Kind is UTC)
$localDate = Get-Date
# Translate it to Eastern Standard time, as a [datetimeoffset] instance.
# Note: Casting $localDate to [datetimeoffset] is crucial to ensure
# that a [datetimeoffset] with the proper UTC offset is returned.
# Without it, you'd get a [datetime] instance that is nominally
# the correct time, but has an Unspecified .Kind value.
# Also, only a [datetimeoffset] instance includes a UTC offset
# when stringified with format string 'o'
$dtoEST = [TimeZoneInfo]::ConvertTimeBySystemTimeZoneId(
[datetimeoffset] $localDate,
'Eastern Standard Time'
)
# Format according to ISO 8601 with UTC offset, but remove the
# fractional-seconds part:
$dtoEST.ToString('o') -replace '\.\d+(?=-)'
The above yields a string such as '2020-01-23T16:44:41-05:00'
.
Related Topics
System.Drawing Out of Memory Exception
How to I Apply Filter While Paginating in ASP.NET MVC and Entity Framework
Rotate - Transposing a List<List<String>> Using Linq C#
Why Is Infinity Printed as "8" in the Windows 10 Console
How to Compile a C# File with Roslyn Programmatically
Loading Image from Code Using Relative Path in Windows Forms
How to Get the Correct Ip from Http_X_Forwarded_For If It Contains Multiple Ip Addresses
Access Form Component from Another Class
Ilookup<Tkey, Tval> VS. Igrouping<Tkey, Tval>
How to Tell If My Application Is Running as a 32-Bit or 64-Bit Application
How to Get the Location of the Dll Currently Executing
Return List Using Select New in Linq
Create a .Txt File If Doesn't Exist, and If It Does Append a New Line