Programming」カテゴリーアーカイブ

プログラミング全般に関するカテゴリーです。

Pythonで日付を扱う場合のTips

Pythonで日付を扱いたい場合、datetimeを使うと便利です。

使い方は次のような感じです。

文字列型とdatetime型の変換

datetime型から文字列型に変換

>>> import datetime
>>> date = datetime.datetime(2020, 2, 11)
>>> date.strftime('%Y/%m/%d')
'2020/02/11'

文字列型からdatetime型に変換

>>> datetime.datetime.strptime('2020/02/11', '%Y/%m/%d')
datetime.datetime(2020, 2, 11, 0, 0)

日数の差を計算

>>> date1 = datetime.datetime.(2020, 2, 11)
>>> date2 = datetime.datetime.(2019, 2, 11)
>>> (date1 - date2).days
365

何日か後の日付を計算

>>> date = datetime.datetime.(2019, 2, 11)
>>> date + datetime.timedelta(days=365)
datetime.datetime(2020, 2, 11, 0, 0)

月の日数を調べる

calendarを使って次のような感じで取得できます。

>>> import calendar
>>> calendar.monthrange(2020, 2)[1]
29

1年は12パターンしかありませんが、うるう年も計算してくれるので便利です。

リンク

datetime — Basic date and time types — Python 3.8.2 documentation
https://docs.python.org/3/library/datetime.html

calendar — General calendar-related functions — Python 3.8.2 documentation
https://docs.python.org/3/library/calendar.html

C#で文字列の分割

C#ではSplitというメソッドを使うことで簡単に文字列の分割ができます。
使い方は次のような感じです。

コンマ「,」かハイフン「-」で分割

using System;

class Example1
{
  static public void Main()
  {
    string str = "one,two-three";
    char[] sep = { ',', '-' };

    string[] ar = str.Split(sep, StringSplitOptions.None);

    foreach(string s in ar) {
      Console.WriteLine(s);
    }
  }
}

実行結果

one
two
three

連続した3つのハイフン「---」で分割

using System;

class Example2
{
  static public void Main()
  {
    string str = "one---two-three";
    string[] sep = { "---" };

    string[] ar = str.Split(sep, StringSplitOptions.None);

    foreach(string s in ar) {
      Console.WriteLine(s);
    }
  }
}

実行結果

one
two-three

他に、正規表現を使って分割したりもできます。

リンク

String.Split Method (System) | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/api/system.string.split

文字列に合わせたUI.Textのサイズを取得する方法

UnityのUI.Textで、実際にテキストを表示した際のサイズが知りたい場合はpreferredWidthpreferredHeightを使って調べることができるそうです。

使い方

Text text;

float width = text.preferredWidth;
float height = text.preferredHeight;

テキストのサイズに合わせてUIを調整したい場合に便利かなと思います。

TextMeshPro

TexhMeshProの場合もpreferredWidthpreferredHeightを使って実際のサイズを調べることができるようです。

使い方

TMPro.TextMeshProUGUI text;

float width = text.preferredWidth;
float height = text.preferredHeight;

リンク

Unity – Scripting API: ILayoutElement
https://docs.unity3d.com/ScriptReference/UI.ILayoutElement.html

Class TextMeshProUGUI | TextMeshPro | 1.5.6
https://docs.unity3d.com/Packages/[email protected]/api/TMPro.TextMeshProUGUI.html